
package com.rt.schedulenew.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rt.schedulebase.dto.*;
import com.rt.schedulebase.entity.*;
import com.rt.schedulebase.mapper.*;
import com.rt.schedulenew.api.*;
import com.rt.schedulenew.utils.base.BigDecimalUtil;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.base.ConstantsUtil;
import com.rt.schedulenew.utils.global.JsonResult;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.pkgenerator.PKGeneratorSingle;
import com.rt.schedulenew.utils.util.DateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ExamScheduleServiceImpl extends ServiceImpl<ExamScheduleMapper, ExamSchedule> implements IExamScheduleService {
    private static Logger log = LoggerFactory.getLogger(ExamScheduleServiceImpl.class);
    @Autowired
    private IDictExamQueueService dictExamQueueService;
    @Resource
    private ExamScheduleMapper examScheduleMapper;
    @Resource
    private ExamScheduleItemMapper examScheduleItemMapper;
    @Resource
    private ExamApplyItemMapper examApplyItemMapper;
    @Resource
    private ExamReferMapper examReferMapper;
    @Resource
    private ExamReferItemMapper examReferItemMapper;
    @Autowired
    private IDictScheduleApmService dictScheduleApmService;
    @Autowired
    private ConfigServiceImpl configService;
    @Autowired
    private ISourceService sourceService;
    @Resource
    private ExamScheduleApmMapper examScheduleApmMapper;
    @Autowired
    private IExamScheduleService examScheduleService;
    @Autowired
    private IExamScheduleItemService examScheduleItemService;
    @Autowired
    private CommonServiceImpl commonServiceImpl;
    @Autowired
    private IDictScheduleApmRegularService dictScheduleApmRegularService;
    @Resource
    private ExamApplyMapper examApplyMapper;
    @Autowired
    private IExamApplyItemService examApplyItemService;
    @Autowired
    private IExamApplyService examApplyService;
    @Autowired
    private IScheduleSignService scheduleSignService;
    @Autowired
    private IExamApplyOrganService examApplyOrganService;
    @Autowired
    private IExamScheduleApmService examScheduleApmService;

    /***
     * 获取预约统计的分组模板
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> getScheduleDetailSum(ExamScheduleDto dto) {
        boolean isExamClass4Organ = configService.getOrganExamClassList().contains(dto.getExamClass());
        // 是否分时段预约
        String isApmFlag = StringUtils.isNotBlank(dto.getIsApmFlag()) ? dto.getIsApmFlag() : "0";
        // 是否循环号源
        String isRecycleSource = StringUtils.isNotBlank(dto.getIsRecycleSource()) ? dto.getIsRecycleSource() : "0";
        try {
            List<String> queueNames = new ArrayList<>();
            if (StringUtils.isNotBlank(dto.getQueueName())) {
                queueNames = CommonUtil.split2List(dto.getQueueName());
                dto.setQueueName(null);
            } else {
                DictExamQueueDto dictExamQueueDto = new DictExamQueueDto();
                dictExamQueueDto.setDeptCode(dto.getDeptCode());
                dictExamQueueDto.setExamClass(dto.getExamClass());
                dictExamQueueDto.setLocation(dto.getLocation());
                dictExamQueueDto.setZoneName(dto.getZoneName());
                List<DictExamQueue> dictExamQueueList = dictExamQueueService.getQueueNameList(dictExamQueueDto);
                if (CollectionUtils.isNotEmpty(dictExamQueueList)) {
                    return new HashMap<>();
                }
                for (DictExamQueue queue : dictExamQueueList) {
                    queueNames.add(queue.getQueueName());
                }
            }
            dto.setQueueNames(queueNames);
            dto.setWeekDate(DateUtil.getWeek(dto.getScheduledDate()));

            DictScheduleApmDto dsaDto = new DictScheduleApmDto();
            dsaDto.setQueueNames(dto.getQueueNames());
            dsaDto.setScheduleApm(dto.getScheduleApm());
            dsaDto.setWeekDate(dto.getWeekDate());
            dsaDto.setScheduleDate(dto.getScheduledDate());
            // 获取队列下的通用时段列表
            List<DictScheduleApm> genericScheduleApms = dictScheduleApmService.getNormalSchedule(dsaDto);
            List<DictScheduleApm> dateScheduleApms = dictScheduleApmService.getDateScheduleApms(dsaDto);
            if (CollectionUtils.isEmpty(genericScheduleApms)
                    && CollectionUtils.isEmpty(dateScheduleApms)) {
                return new HashMap<>();
            }
            List<DictScheduleApm> weekDateScheduleApms = dictScheduleApmService.getWeekDateScheduleApms(dsaDto);
            //genericScheduleApms = genericScheduleApms.stream().filter(x -> x.getStopFlag().equals("0")).collect(Collectors.toList());
            // List<DictScheduleApm> dateScheduleApms = dictScheduleApmService.getDateScheduleApms(dsaDto);
            //genericScheduleApms = genericScheduleApms.stream().filter(x -> x.getStopFlag().equals("0")).collect(Collectors.toList());

            // 日期可以使用的时段列表
            List<DictScheduleApm> usefulApms = getScheduleRegular(dateScheduleApms, weekDateScheduleApms, genericScheduleApms);

            // 获取预约记录列表
            List<ExamSchedule> scheduleList = examScheduleMapper.getExamSchedule(dto);
            List<ScheduleDetailDto> apmScheduleDetail = getExamSchedule4Ratio(usefulApms, scheduleList, isExamClass4Organ, dto);
            if ("1".equals(isApmFlag)) {
                apmScheduleDetail = getScheduleConvertApmFlag(apmScheduleDetail);
            }
            Map<String, Object> map = new HashMap<>();
            String title = "已约申请单数 / 限制申请单数";
            if (isExamClass4Organ) {
                boolean isShowApplyNumber = configService.isOpenConfig(ConstantsUtil.ConfigName.IS_SHOW_APPLY_NUMBER.getKey());
                if (isShowApplyNumber) {
                    title = "已预约占用系数 / 系数限制";
                } else {
                    title = "已约申请单数 / 已预约占用系数 / 系数限制";
                }
            }
            map.put("title", title);
            String columnStr = getColumnString(dto, queueNames);
            map.put("column", JSON.parse(columnStr));
            // 获取预约数据列表
            List<Map<String, String>> lima = getScheduleDataGrid(apmScheduleDetail, queueNames, isExamClass4Organ, isApmFlag, isRecycleSource);
            map.put("data", lima);
            map.put("scheduleDetails", apmScheduleDetail);
            return map;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public Map<String, Object> getQueueCount(ExamScheduleDto dto) {
        List<ExamScheduleDto> liExam = examScheduleMapper.getQueueCount(dto);
        for (ExamScheduleDto scheduleDto : liExam) {
            double spanApmRatio = 0.0;
            Double curScheduledRatio = 0.0;
            if (StringUtils.isNotBlank(scheduleDto.getNextApmRatio())) {
                String[] split = scheduleDto.getNextApmRatio().split("\\|");
                for (String str : split) {
                    spanApmRatio += Double.parseDouble(str.substring(str.indexOf("=") + 1));
                }
                curScheduledRatio = scheduleDto.getOrgans() - spanApmRatio;
            } else {
                curScheduledRatio = scheduleDto.getOrgans();
            }
            new StringBuilder().append(curScheduledRatio / scheduleDto.getMaxLimit() * 100.0).append("%").toString();
        }
        return null;
    }

    private List<DictScheduleApm> getScheduleRegular(List<DictScheduleApm> dateApms, List<DictScheduleApm> weekApms, List<DictScheduleApm> genericApms) {
        List<DictScheduleApm> result = new ArrayList<>();
        //int indexNo = 0;
        if (CollectionUtils.isNotEmpty(weekApms)) {
            // 如果周时段和通用时段重合取周时段
            for (DictScheduleApm dsrWeek : weekApms) {
                for (DictScheduleApm dsrNormal : genericApms) {
                    if (dsrWeek.getQueueName().equals(dsrNormal.getQueueName())
                            && dsrWeek.getTimeStart().equals(dsrNormal.getTimeStart())
                            && dsrWeek.getTimeEnd().equals(dsrNormal.getTimeEnd())) {
                        result.add(dsrWeek);
                    } else {
                        result.add(dsrNormal);
                    }
                }
            }
        } else {
            result.addAll(genericApms);
        }
        // 如果日期时段不为空-将时间段相同的通用号源替换成
        if (CollectionUtils.isNotEmpty(dateApms)) {
            List<DictScheduleApm> dateScheduleApms = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(result)) {
                for (DictScheduleApm dsrNormal : result) {
                    DictScheduleApm apm = dateApms.stream().filter(dsrDate -> dsrDate.getQueueName().equals(dsrNormal.getQueueName())
                                    && dsrDate.getTimeStart().equals(dsrNormal.getTimeStart())
                                    && dsrDate.getTimeEnd().equals(dsrNormal.getTimeEnd()))
                            .findFirst().orElse(null);
                    if (Objects.nonNull(apm)) {
                        dateScheduleApms.add(apm);
                    } else {
                        dateScheduleApms.add(dsrNormal);
                    }
                }
            } else {
                dateScheduleApms.addAll(dateApms);
            }
            return dateScheduleApms;
        }
        return result;
    }

    /**
     * 计算预约数量的比例
     *
     * @param apmList           时段列表
     * @param scheduleList      时段的预约列表
     * @param isExamClass4Organ 是否按系数 true 按人次 false 按检查项目系数
     * @param examScheduleDto
     * @return
     */
    private List<ScheduleDetailDto> getExamSchedule4Ratio(List<DictScheduleApm> apmList, List<ExamSchedule> scheduleList, boolean isExamClass4Organ, ExamScheduleDto examScheduleDto) {
        // 午别标志
        String isApmFlag = StringUtils.isNotBlank(examScheduleDto.getIsApmFlag()) ? examScheduleDto.getIsApmFlag() : "0";
        // 循环号源
        String isRecycleSource = StringUtils.isNotBlank(examScheduleDto.getIsRecycleSource()) ? examScheduleDto.getIsRecycleSource() : "0";
        Map<String, ScheduleDetailDto> apmMaps = new HashMap<>();
        // 构造每个时段的信息 总量 、 循环号数、
        for (DictScheduleApm dsr : apmList) {
            ScheduleDetailDto detailDto = new ScheduleDetailDto();
            detailDto.setQueueName(dsr.getQueueName());
            detailDto.setScheduleApm(dsr.getScheduleApm());
            detailDto.setApmFlag(dsr.getApmFlag());
            detailDto.setStopFlag(dsr.getStopFlag());
            detailDto.setTimeStart(dsr.getTimeStart());
            detailDto.setTimeEnd(dsr.getTimeEnd());
            detailDto.setCurScheduledCount(0);
            detailDto.setCurScheduledRatio(0.0);
            if (isExamClass4Organ) {
                detailDto.setItemLimit((dsr.getMaxLimit() != null) ? dsr.getMaxLimit() : 0.0);
                detailDto.setCountLimit(0);
            } else {
                detailDto.setItemLimit(0.0);
                detailDto.setCountLimit((dsr.getMaxLimit() != null) ? Integer.parseInt(dsr.getMaxLimit().toString().replaceAll("\\.0", "")) : 0);
            }
            if ("1".equals(isRecycleSource)) {
                DictScheduleApmDto dictScheduleApmDto = new DictScheduleApmDto();
                dictScheduleApmDto.setQueueNames(CommonUtil.split2List(dsr.getQueueName()));
                dictScheduleApmDto.setScheduleApm(dsr.getScheduleApm());
                dictScheduleApmDto.setScheduleDate(examScheduleDto.getScheduledDate());
                dictScheduleApmDto.setWeekDate(examScheduleDto.getWeekDate());
                dictScheduleApmDto.setIsRecycleSource(isRecycleSource);
                List<DictScheduleApmDto> dictScheduleApmDtoList = dictScheduleApmService.getScheduleApms(dictScheduleApmDto);
                List<String> apmCodes = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(dictScheduleApmDtoList)) {
                    for (DictScheduleApmDto apmDto : dictScheduleApmDtoList) {
                        apmCodes.add(apmDto.getApmCode());
                    }
                    ExamScheduleApm examScheduleapm = commonServiceImpl.examScheduleApm(examScheduleDto.getScheduledDate(), apmCodes, examScheduleDto.getExamClass());
                    if (examScheduleapm != null) {
                        detailDto.setCurCountRecycle(examScheduleapm.getCountRecycle());
                        detailDto.setCurOrgansRecycle(examScheduleapm.getOrgansRecycle());
                    }
                }
            }
            apmMaps.put(dsr.getScheduleApm() + "_" + dsr.getQueueName(), detailDto);
        }
        // 根据预约列表-计算每个时段的已预约数量
        if (CollectionUtils.isNotEmpty(scheduleList)) {
            for (ExamSchedule es : scheduleList) {
                String queueName = es.getQueueName();
                String scheduledDate = es.getScheduledDate();
                String scheduleApm = es.getScheduleApm();
                String scheduledId = es.getScheduledId();
                String nextApmRatio = es.getNextApmRatio();
                Double organs = es.getOrgans();
                String key = scheduleApm + "_" + queueName;
                ScheduleDetailDto dto = apmMaps.get(key);
                if (dto == null) {
                    continue;
                }
                dto.setCurScheduledCount(dto.getCurScheduledCount() + 1);
                if (!isExamClass4Organ) {
                    apmMaps.put(key, dto);
                    continue;
                }
                Map<String, Object> map = getScheduledRatioAndSpanApmRatio(scheduleApm, scheduledId, nextApmRatio, organs);
                double curScheduledRatio = (double) map.get("curScheduledRatio");
                String spanApmRatioStr = map.get("spanApmRatioStr").toString();
                if (StringUtils.isNotBlank(dto.getSpanApmRatioStr())) {
                    spanApmRatioStr = dto.getSpanApmRatioStr() + ";" + spanApmRatioStr;
                }
                dto.setCurScheduledRatio(dto.getCurScheduledRatio() + curScheduledRatio);

                if ("1".equals(isApmFlag)) {
                    String apmFlag = dto.getApmFlag();
                    String spanApmRatioStrNew = "";
                    String[] split = spanApmRatioStr.split(";");
                    for (String arr : split) {
                        String[] scheduleApmArr = arr.split("_");
                        String schedule4ApmFlag = "";
                        if (ConstantsUtil.DictScheduleApmFlag.MORNING.getKey().equals(apmFlag)) {
                            schedule4ApmFlag = ConstantsUtil.DictScheduleApmFlag.MORNING.getValue();
                        } else if (ConstantsUtil.DictScheduleApmFlag.NOON.getKey().equals(apmFlag)) {
                            schedule4ApmFlag = ConstantsUtil.DictScheduleApmFlag.NOON.getValue();
                        } else if (ConstantsUtil.DictScheduleApmFlag.AFTERNOON.getKey().equals(apmFlag)) {
                            schedule4ApmFlag = ConstantsUtil.DictScheduleApmFlag.AFTERNOON.getValue();
                        } else if (ConstantsUtil.DictScheduleApmFlag.NIGHT.getKey().equals(apmFlag)) {
                            schedule4ApmFlag = ConstantsUtil.DictScheduleApmFlag.NIGHT.getValue();
                        } else {
                            schedule4ApmFlag = ConstantsUtil.DictScheduleApmFlag.ALLDAY.getValue();
                        }
                        spanApmRatioStrNew = spanApmRatioStrNew + ";" + scheduleApmArr[0] + "_" + schedule4ApmFlag + "_" + scheduleApmArr[2];
                    }
                    spanApmRatioStr = spanApmRatioStrNew.substring(1);
                }
                dto.setSpanApmRatioStr(spanApmRatioStr);
                apmMaps.put(key, dto);
                if (!StringUtils.isNotBlank(nextApmRatio)) {
                    continue;
                }
                String[] split2 = nextApmRatio.split("\\|");
                for (String str : split2) {
                    String[] arr3 = str.split("=");
                    DictScheduleApm dsa = dictScheduleApmService.selectOneByApmCode(arr3[0]);
                    String apm = dsa.getScheduleApm();
                    double ratio = Double.parseDouble(arr3[1]);
                    String key2 = apm + "_" + queueName;
                    ScheduleDetailDto dto2 = apmMaps.get(key2);
                    if (dto2 != null) {
                        dto2.setCurScheduledRatio(dto2.getCurScheduledRatio() + ratio);
                        apmMaps.put(key2, dto2);
                    }
                }
            }
        }
        List<ScheduleDetailDto> list = new ArrayList<>(apmMaps.values());
        Collections.sort(list, Comparator.comparing(ScheduleDetailDto::getTimeStart));
        return list;
    }

    private List<ScheduleDetailDto> getExamSchedule4Ratio_v2(List<DictScheduleApm> liApm, ExamScheduleDto dto, boolean isExamClass4Organ, String isApmFlag) {
        Map<String, ScheduleDetailDto> map_apm = new HashMap<String, ScheduleDetailDto>();
        for (DictScheduleApm dsr : liApm) {
            ScheduleDetailDto detailDto = new ScheduleDetailDto();
            detailDto.setQueueName(dsr.getQueueName());
            detailDto.setScheduleApm(dsr.getScheduleApm());
            detailDto.setApmFlag(dsr.getApmFlag());
            detailDto.setStopFlag(dsr.getStopFlag());
            ExamScheduleApm examScheduleApm = commonServiceImpl.examScheduleApm(dto.getScheduledDate(), Arrays.asList(dsr.getApmCode()), "");
            if (examScheduleApm != null) {
                detailDto.setCurScheduledCount(Integer.valueOf((examScheduleApm.getCount() != null) ? examScheduleApm.getCount() : 0));
                detailDto.setCurScheduledRatio(Double.valueOf((examScheduleApm.getOrgans() != null) ? examScheduleApm.getOrgans() : 0.0));
            } else {
                detailDto.setCurScheduledCount(Integer.valueOf(0));
                detailDto.setCurScheduledRatio(Double.valueOf(0.0));
            }
            if (isExamClass4Organ) {
                detailDto.setItemLimit(Double.valueOf((dsr.getMaxLimit() != null) ? dsr.getMaxLimit() : 0.0));
                detailDto.setCountLimit(Integer.valueOf(0));
            } else {
                detailDto.setItemLimit(Double.valueOf(0.0));
                detailDto.setCountLimit(Integer.valueOf((dsr.getMaxLimit() != null) ? Integer.parseInt(dsr.getMaxLimit().toString().replaceAll("\\.0", "")) : 0));
            }
            map_apm.put(dsr.getScheduleApm() + "_" + dsr.getQueueName(), detailDto);
        }
        List<ScheduleDetailDto> list = new ArrayList<ScheduleDetailDto>();
        Object[] keys = map_apm.keySet().toArray();
        Arrays.sort(keys);
        for (Object key : keys) {
            list.add(map_apm.get(key));
        }
        return list;
    }

    private List<ScheduleDetailDto> getScheduleConvertApmFlag(List<ScheduleDetailDto> liDto) {
        DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
        df.setMaximumFractionDigits(1);
        Map<String, ScheduleDetailDto> theSameApmCountMap = new HashMap<>();
        ScheduleDetailDto scheduleDetailDtoNew = null;
        for (ScheduleDetailDto dto : liDto) {
            scheduleDetailDtoNew = new ScheduleDetailDto();
            scheduleDetailDtoNew.setQueueName(dto.getQueueName());
            scheduleDetailDtoNew.setStopFlag(dto.getStopFlag());
            scheduleDetailDtoNew.setApmFlag(dto.getApmFlag());
            scheduleDetailDtoNew.setExamClass(dto.getExamClass());
            scheduleDetailDtoNew.setScheduledDate(dto.getScheduledDate());
            String spanApmRatioStr = "";
            if (!theSameApmCountMap.containsKey(dto.getQueueName() + "_" + dto.getApmFlag())) {
                scheduleDetailDtoNew.setCurScheduledCount(dto.getCurScheduledCount());
                scheduleDetailDtoNew.setCurScheduledRatio(Double.parseDouble(df.format(dto.getCurScheduledRatio())));
                scheduleDetailDtoNew.setCountLimit("1".equals(dto.getStopFlag()) ? 0 : dto.getCountLimit());
                scheduleDetailDtoNew.setItemLimit("1".equals(dto.getStopFlag()) ? 0.0 : Double.parseDouble(df.format(dto.getItemLimit())));
                scheduleDetailDtoNew.setSpanApmRatioStr(StringUtils.isNotBlank(dto.getSpanApmRatioStr()) ? dto.getSpanApmRatioStr() : "");
                scheduleDetailDtoNew.setCurCountRecycle(dto.getCurCountRecycle());
                scheduleDetailDtoNew.setCurOrgansRecycle(Double.parseDouble(df.format(dto.getCurOrgansRecycle())));
            } else {
                scheduleDetailDtoNew = theSameApmCountMap.get(dto.getQueueName() + "_" + dto.getApmFlag());
                scheduleDetailDtoNew.setCurScheduledCount(scheduleDetailDtoNew.getCurScheduledCount() + dto.getCurScheduledCount());
                scheduleDetailDtoNew.setCurScheduledRatio(scheduleDetailDtoNew.getCurScheduledRatio() + Double.parseDouble(df.format(dto.getCurScheduledRatio())));
                scheduleDetailDtoNew.setCountLimit(scheduleDetailDtoNew.getCountLimit() + ("1".equals(dto.getStopFlag()) ? 0 : dto.getCountLimit()));
                scheduleDetailDtoNew.setItemLimit(scheduleDetailDtoNew.getItemLimit() + ("1".equals(dto.getStopFlag()) ? 0.0 : Double.parseDouble(df.format(dto.getItemLimit()))));
                if (StringUtils.isNotBlank(scheduleDetailDtoNew.getSpanApmRatioStr())) {
                    if (StringUtils.isNotBlank(dto.getSpanApmRatioStr())) {
                        spanApmRatioStr = scheduleDetailDtoNew.getSpanApmRatioStr() + ";" + dto.getSpanApmRatioStr();
                    } else {
                        spanApmRatioStr = scheduleDetailDtoNew.getSpanApmRatioStr();
                    }
                } else {
                    spanApmRatioStr = (StringUtils.isNotBlank(dto.getSpanApmRatioStr()) ? dto.getSpanApmRatioStr() : "");
                }
                scheduleDetailDtoNew.setSpanApmRatioStr(spanApmRatioStr);
                scheduleDetailDtoNew.setCurCountRecycle(scheduleDetailDtoNew.getCurCountRecycle() + dto.getCurCountRecycle());
                scheduleDetailDtoNew.setCurOrgansRecycle(scheduleDetailDtoNew.getCurOrgansRecycle() + Double.parseDouble(df.format(dto.getCurOrgansRecycle())));
            }
            if (ConstantsUtil.DictScheduleApmFlag.MORNING.getKey().equals(dto.getApmFlag())) {
                scheduleDetailDtoNew.setScheduleApm(ConstantsUtil.DictScheduleApmFlag.MORNING.getValue());
                scheduleDetailDtoNew.setSortNo("1");
            } else if (ConstantsUtil.DictScheduleApmFlag.NOON.getKey().equals(dto.getApmFlag())) {
                scheduleDetailDtoNew.setScheduleApm(ConstantsUtil.DictScheduleApmFlag.NOON.getValue());
                scheduleDetailDtoNew.setSortNo("2");
            } else if (ConstantsUtil.DictScheduleApmFlag.AFTERNOON.getKey().equals(dto.getApmFlag())) {
                scheduleDetailDtoNew.setScheduleApm(ConstantsUtil.DictScheduleApmFlag.AFTERNOON.getValue());
                scheduleDetailDtoNew.setSortNo("3");
            } else if (ConstantsUtil.DictScheduleApmFlag.NIGHT.getKey().equals(dto.getApmFlag())) {
                scheduleDetailDtoNew.setScheduleApm(ConstantsUtil.DictScheduleApmFlag.NIGHT.getValue());
                scheduleDetailDtoNew.setSortNo("4");
            } else {
                scheduleDetailDtoNew.setScheduleApm(ConstantsUtil.DictScheduleApmFlag.ALLDAY.getValue());
                scheduleDetailDtoNew.setSortNo("5");
            }
            theSameApmCountMap.put(dto.getQueueName() + "_" + dto.getApmFlag(), scheduleDetailDtoNew);
        }
        List<ScheduleDetailDto> resultList = new ArrayList<>();
        Object[] keys = theSameApmCountMap.keySet().toArray();
        Arrays.sort(keys);
        for (Object key : keys) {
            resultList.add(theSameApmCountMap.get(key));
        }
        Collections.sort(resultList, Comparator.comparing(ScheduleDetailDto::getSortNo));
        return resultList;
    }

    private String getColumnString(ExamScheduleDto dto, List<String> li) {
        String s = "[{\"prop\":\"apm\",\"label\":\"" + dto.getScheduledDate() + "\",\"queueName\":\"" + dto.getScheduledDate() + "\"},";
        for (int i = 0; i < li.size(); ++i) {
            DictExamQueueDto dictExamQueueDto = new DictExamQueueDto();
            dictExamQueueDto.setDeptCode(dto.getDeptCode());
            dictExamQueueDto.setExamClass(dto.getExamClass());
            dictExamQueueDto.setQueueName((String) li.get(i));
            List<DictExamQueue> dictExamQueueList = (List<DictExamQueue>) dictExamQueueService.getQueueNameList((DictExamQueue) dictExamQueueDto);
            String queueName = li.get(i);
            String queueAlias = li.get(i);
            if (dictExamQueueList != null && !dictExamQueueList.isEmpty() && StringUtils.isNotBlank(dictExamQueueList.get(0).getQueueAlias())) {
                queueAlias = dictExamQueueList.get(0).getQueueAlias();
            }
            s = s + "{\"prop\":\"queue" + i + "\",\"label\":\"" + queueAlias + "\",\"queueName\":\"" + queueName + "\"},";
            if ("1".equals(dto.getIsRecycleSource())) {
                s = s + "{\"prop\":\"queue" + i + "_recycle\",\"label\":\"" + queueAlias + "\",\"queueName\":\"" + queueName + "\"},";
            }
        }
        if ("1".equals(dto.getIsRecycleSource())) {
            s += "{\"prop\":\"apmHj\",\"label\":\"合计\",\"queueName\":\"合计\"},{\"prop\":\"apmHj_recycle\",\"label\":\"合计\",\"queueName\":\"合计\"}]";
        } else {
            s += "{\"prop\":\"apmHj\",\"label\":\"合计\",\"queueName\":\"合计\"}]";
        }
        return s;
    }

    /**
     * 获取预约量数据表格
     *
     * @param liDto
     * @param queueNames
     * @param isExamClass4Organ
     * @param isApmFlag
     * @param isRecycleSource
     * @return
     */
    private List<Map<String, String>> getScheduleDataGrid(List<ScheduleDetailDto> liDto, List<String> queueNames, boolean isExamClass4Organ, String isApmFlag, String isRecycleSource) {
        DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
        df.setMaximumFractionDigits(1);
        Map<String, Object> m_queue = new HashMap<>();
        int queueCnt = queueNames.size();
        for (int i = 0; i < queueCnt; ++i) {
            m_queue.put(queueNames.get(i), String.valueOf(i));
        }
        Map<String, List<String>> m_queue_all = new HashMap<>();
        List<String> queue_hj_list = new ArrayList<>();
        Map<String, List<String>> m_queue_all_recycle = new HashMap<>();
        List<String> queue_hj_list_recycle = new ArrayList<>();
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> m = new HashMap<>();
        List<String> apmList = new ArrayList<>();
        for (ScheduleDetailDto dto : liDto) {
            String scheduleApm = dto.getScheduleApm();
            DictExamQueue dictExamQueue = new DictExamQueue();
            dictExamQueue.setQueueName(dto.getQueueName());
            dictExamQueue.setExamClass(dto.getExamClass());
            List<DictExamQueue> dictExamQueueList = dictExamQueueService.getQueueNameList(dictExamQueue);
            DictExamQueue examQueue = dictExamQueueList.get(0);
            if (!apmList.contains(scheduleApm)) {
                if (MapUtils.isNotEmpty(m)) {
                    double[] sums = new double[3];
                    int len = 2;
                    for (int k = 0; k < queueCnt; ++k) {
                        if (m.get("queue" + k) == null) {
                            continue;
                        }

                        String[] arr = m.get("queue" + k).split("/");
                        len = arr.length;
                        for (int l = 0; l < len; ++l) {
                            BigDecimal bd1 = BigDecimal.valueOf(sums[l]);
                            BigDecimal bd2 = new BigDecimal(arr[l].replaceAll(",", ""));
                            sums[l] = bd1.add(bd2).doubleValue();
                        }
                    }
                    String apm_hj = "";
                    if (len == 2) {
                        apm_hj = sums[0] + "/" + sums[1];
                    } else if (len == 3) {
                        apm_hj = sums[0] + "/" + df.format(sums[1]) + "/" + sums[2];
                    }
                    apm_hj = apm_hj.replaceAll("\\.0", "");
                    queue_hj_list.add(apm_hj);
                    m.put("apmHj", apm_hj);
                    if ("1".equals(isRecycleSource)) {
                        BigDecimal cur_recycle = new BigDecimal(0);
                        for (int j2 = 0; j2 < queueCnt; ++j2) {
                            String cur_recycle_count = m.get("queue" + j2 + "_recycle");
                            if (StringUtils.isNotBlank(cur_recycle_count)) {
                                BigDecimal bd3 = new BigDecimal(cur_recycle_count.replaceAll(",", ""));
                                cur_recycle = cur_recycle.add(bd3);
                            }
                        }
                        String apm_hj_recycle = String.valueOf(df.format(cur_recycle.doubleValue())).replaceAll("\\.0", "");
                        queue_hj_list_recycle.add(apm_hj_recycle);
                        m.put("apmHj_recycle", apm_hj_recycle);
                    }
                    list.add(m);
                }
                m = new HashMap<>();
                m.put("apm", scheduleApm);
                apmList.add(scheduleApm);
            }
            if (isExamClass4Organ) {
                boolean isShowApplyNumber = configService.isOpenConfig(ConstantsUtil.ConfigName.IS_SHOW_APPLY_NUMBER.getKey());
                String queue_val = "";
                if (isShowApplyNumber) {
                    if ("1".equals(isApmFlag)) {
                        if ("1".equals(examQueue.getUseFlag())) {
                            queue_val = df.format(dto.getCurScheduledRatio()) + "/0";
                        } else {
                            queue_val = df.format(dto.getCurScheduledRatio()) + "/" + dto.getItemLimit();
                        }
                    } else if ("1".equals(examQueue.getUseFlag())) {
                        queue_val = df.format(dto.getCurScheduledRatio()) + "/0";
                    } else {
                        queue_val = ("1".equals(dto.getStopFlag()) ? (df.format(dto.getCurScheduledRatio()) + "/0") : (df.format(dto.getCurScheduledRatio()) + "/" + dto.getItemLimit()));
                    }
                } else if ("1".equals(isApmFlag)) {
                    if ("1".equals(examQueue.getUseFlag())) {
                        queue_val = dto.getCurScheduledCount() + "/" + df.format(dto.getCurScheduledRatio()) + "/0";
                    } else {
                        queue_val = dto.getCurScheduledCount() + "/" + df.format(dto.getCurScheduledRatio()) + "/" + dto.getItemLimit();
                    }
                } else if ("1".equals(examQueue.getUseFlag())) {
                    queue_val = dto.getCurScheduledCount() + "/" + df.format(dto.getCurScheduledRatio()) + "/0";
                } else {
                    queue_val = ("1".equals(dto.getStopFlag()) ? (dto.getCurScheduledCount() + "/" + df.format(dto.getCurScheduledRatio()) + "/0") : (dto.getCurScheduledCount() + "/" + df.format(dto.getCurScheduledRatio()) + "/" + dto.getItemLimit()));
                }
                queue_val = queue_val.replaceAll("\\.0", "");
                m.put("queue" + m_queue.get(dto.getQueueName()), queue_val);
                m.put("spanApmRatio" + m_queue.get(dto.getQueueName()), dto.getSpanApmRatioStr());
                m.put("queue" + m_queue.get(dto.getQueueName()) + "_recycle", String.valueOf(dto.getCurOrgansRecycle()).replaceAll("\\.0", ""));
            } else {
                String queue_val2 = "";
                if ("1".equals(isApmFlag)) {
                    if ("1".equals(examQueue.getUseFlag())) {
                        queue_val2 = dto.getCurScheduledCount() + "/0";
                    } else {
                        queue_val2 = dto.getCurScheduledCount() + "/" + dto.getCountLimit();
                    }
                } else if ("1".equals(examQueue.getUseFlag())) {
                    queue_val2 = dto.getCurScheduledCount() + "/0";
                } else {
                    queue_val2 = ("1".equals(dto.getStopFlag()) ? (dto.getCurScheduledCount() + "/0") : (dto.getCurScheduledCount() + "/" + dto.getCountLimit()));
                }
                m.put("queue" + m_queue.get(dto.getQueueName()), queue_val2);
                m.put("queue" + m_queue.get(dto.getQueueName()) + "_recycle", String.valueOf(dto.getCurCountRecycle()));
            }
            String key = "queue" + m_queue.get(dto.getQueueName());
            List<String> queue_apm_list = null;
            if (m_queue_all.containsKey(key)) {
                queue_apm_list = m_queue_all.get(key);
            } else {
                queue_apm_list = new ArrayList<String>();
            }
            queue_apm_list.add(m.get(key));
            m_queue_all.put(key, queue_apm_list);
            if ("1".equals(isRecycleSource)) {
                String key_recycle = "queue" + m_queue.get(dto.getQueueName()) + "_recycle";
                List<String> queue_apm_list_recycle = null;
                if (m_queue_all_recycle.containsKey(key_recycle)) {
                    queue_apm_list_recycle = m_queue_all_recycle.get(key_recycle);
                } else {
                    queue_apm_list_recycle = new ArrayList<String>();
                }
                queue_apm_list_recycle.add(m.get(key_recycle));
                m_queue_all_recycle.put(key_recycle, queue_apm_list_recycle);
            }
        }
        double[] sums2 = new double[3];
        int len2 = 2;
        for (int j3 = 0; j3 < queueCnt; ++j3) {
            String j3str = m.get("queue" + j3);
            if (j3str == null) {
                continue;
            }

            String[] arr2 = j3str.split("/");
            len2 = arr2.length;
            for (int k2 = 0; k2 < len2; ++k2) {
                BigDecimal bd4 = BigDecimal.valueOf(sums2[k2]);
                BigDecimal bd5 = new BigDecimal(arr2[k2].replaceAll(",", ""));
                sums2[k2] = bd4.add(bd5).doubleValue();
            }
        }
        String apm_hj2 = "";
        if (len2 == 2) {
            apm_hj2 = sums2[0] + "/" + sums2[1];
        } else if (len2 == 3) {
            apm_hj2 = sums2[0] + "/" + df.format(sums2[1]) + "/" + sums2[2];
        }
        apm_hj2 = apm_hj2.replaceAll("\\.0", "");
        queue_hj_list.add(apm_hj2);
        m_queue_all.put("apmHj", queue_hj_list);
        m.put("apmHj", apm_hj2);
        if ("1".equals(isRecycleSource)) {
            BigDecimal cur_recycle2 = new BigDecimal(0);
            for (int j4 = 0; j4 < queueCnt; ++j4) {
                String cur_recycle_count2 = m.get("queue" + j4 + "_recycle");
                if (StringUtils.isNotBlank(cur_recycle_count2)) {
                    BigDecimal bd6 = new BigDecimal(cur_recycle_count2.replaceAll(",", ""));
                    cur_recycle2 = cur_recycle2.add(bd6);
                }
            }
            String apm_hj_recycle2 = String.valueOf(df.format(cur_recycle2.doubleValue())).replaceAll("\\.0", "");
            queue_hj_list_recycle.add(apm_hj_recycle2);
            m_queue_all_recycle.put("apmHj_recycle", queue_hj_list_recycle);
            m.put("apmHj_recycle", apm_hj_recycle2);
        }
        list.add(m);
        m = new HashMap<>();
        m.put("apm", "合计");
        for (String key2 : m_queue_all.keySet()) {
            List<String> list_queue = m_queue_all.get(key2);
            double[] sums_queue = new double[len2];
            for (String str : list_queue) {
                String[] arr = str.split("/");
                for (int l = 0; l < len2; ++l) {
                    BigDecimal bd1 = BigDecimal.valueOf(sums_queue[l]);
                    BigDecimal bd2 = new BigDecimal(arr[l].replaceAll(",", ""));
                    sums_queue[l] = bd1.add(bd2).doubleValue();
                }
            }
            String queue_hj = "";
            if (len2 == 2) {
                queue_hj = sums_queue[0] + "/" + sums_queue[1];
            } else if (len2 == 3) {
                queue_hj = sums_queue[0] + "/" + df.format(sums_queue[1]) + "/" + sums_queue[2];
            }
            queue_hj = queue_hj.replaceAll("\\.0", "");
            m.put(key2, queue_hj);
        }
        if ("1".equals(isRecycleSource)) {
            for (String key_recycle2 : m_queue_all_recycle.keySet()) {
                List<String> list_queue_recycle = m_queue_all_recycle.get(key_recycle2);
                double sums_recycle = 0.0;
                for (String str2 : list_queue_recycle) {
                    if (!str2.contains("/")) {
                        sums_recycle += Double.parseDouble(str2.replaceAll(",", ""));
                    }
                }
                String queue_hj_recycle = String.valueOf(df.format(sums_recycle)).replaceAll("\\.0", "");
                m.put(key_recycle2, queue_hj_recycle);
            }
        }
        list.add(m);
        return list;
    }

    private Map<String, Object> getScheduledRatioAndSpanApmRatio(String scheduleApm, String scheduledId, String nextApmRatio, Double organs) {
        double reqRatio = (organs != null) ? organs : 0.0;
        double spanApmRatio = 0.0;
        String spanApmRatioStr = "";
        if (StringUtils.isNotBlank(nextApmRatio)) {
            String[] split = nextApmRatio.split("\\|");
            for (String str : split) {
                if (StringUtils.isBlank(str)) {
                    continue;
                }
                spanApmRatio += Double.parseDouble(str.substring(str.indexOf("=") + 1));
                spanApmRatioStr = spanApmRatioStr + ";" + scheduledId + "_" + str.replace("=", "_");
            }
        }
        spanApmRatioStr = scheduledId + "_" + scheduleApm + "_" + (reqRatio - spanApmRatio) + spanApmRatioStr;
        double curScheduledRatio = reqRatio - spanApmRatio;
        Map<String, Object> map = new HashMap<>();
        map.put("curScheduledRatio", curScheduledRatio);
        map.put("spanApmRatioStr", spanApmRatioStr);
        return map;
    }

    /**
     * 获取预约数量详情
     *
     * @param dto
     * @return
     */
    @Override
    public List<ExamApplyDto> getScheduleDetailList(ExamScheduleDto dto) {
        boolean isExamClass4Organ = configService.getOrganExamClassList().contains(dto.getExamClass());
        dto.setIsExamClassRatio(isExamClass4Organ);
        List<String> queueNames = new ArrayList<>();
        if ("合计".equals(dto.getQueueName()) || "".equals(dto.getQueueName())) {
            DictExamQueueDto dictExamQueueDto = new DictExamQueueDto();
            dictExamQueueDto.setDeptCode(dto.getDeptCode());
            dictExamQueueDto.setExamClass(dto.getExamClass());
            List<DictExamQueue> dictExamQueueList = dictExamQueueService.getQueueNameList(dictExamQueueDto);
            if (dictExamQueueList != null && !dictExamQueueList.isEmpty()) {
                for (DictExamQueue queue : dictExamQueueList) {
                    queueNames.add(queue.getQueueName());
                }
            }
        } else {
            String queueName = dto.getQueueName();
            queueNames = CommonUtil.split2List(queueName);
        }
        dto.setQueueNames(queueNames);
        if ("合计".equals(dto.getScheduleApm())) {
            dto.setScheduleApm(null);
        } else {
            if (StringUtils.isNotBlank(dto.getApmFlag())) {
                if (ConstantsUtil.DictScheduleApmFlag.MORNING.getValue().equals(dto.getApmFlag())) {
                    dto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.MORNING.getKey());
                } else if (ConstantsUtil.DictScheduleApmFlag.AFTERNOON.getValue().equals(dto.getApmFlag())) {
                    dto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.AFTERNOON.getKey());
                } else if (ConstantsUtil.DictScheduleApmFlag.NIGHT.getValue().equals(dto.getApmFlag())) {
                    dto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.NIGHT.getKey());
                } else if (ConstantsUtil.DictScheduleApmFlag.NOON.getValue().equals(dto.getApmFlag())) {
                    dto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.NOON.getKey());
                } else if ("合计".equals(dto.getApmFlag())) {
                    dto.setApmFlag(null);
                } else {
                    dto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.ALLDAY.getKey());
                }
            }
            DictScheduleApmDto dictScheduleApmDto = new DictScheduleApmDto();
            dictScheduleApmDto.setQueueNames(dto.getQueueNames());
            dictScheduleApmDto.setScheduleDate(dto.getScheduledDate());
            dictScheduleApmDto.setApmFlag(dto.getApmFlag());
            dictScheduleApmDto.setScheduleApm(dto.getScheduleApm());
            dictScheduleApmDto.setWeekDate(DateUtil.getWeek(dto.getScheduledDate()));
            List<DictScheduleApmDto> dictScheduleApmDtoList = dictScheduleApmService.getScheduleApms(dictScheduleApmDto);
            List<String> scheduleApm_new = null;
            List<String> scheduleApmCode_new = null;
            if (CollectionUtils.isNotEmpty(dictScheduleApmDtoList)) {
                scheduleApm_new = new ArrayList<>();
                scheduleApmCode_new = new ArrayList<>();
                for (DictScheduleApmDto apmDto : dictScheduleApmDtoList) {
                    scheduleApm_new.add(apmDto.getScheduleApm());
                    scheduleApmCode_new.add(apmDto.getApmCode());
                }
            }
            dto.setScheduleApms(scheduleApm_new);
            dto.setScheduleApmCodes(scheduleApmCode_new);
        }
        List<String> list_applyNo = new ArrayList<>();
        List<ExamApplyDto> list_result = new ArrayList<>();

        List<ExamApplyDto> scheduleDetailDtoList = examScheduleMapper.getScheduleList(dto);
        if (CollectionUtils.isNotEmpty(scheduleDetailDtoList)) {
            for (ExamApplyDto scheduleDetail : scheduleDetailDtoList) {
                // 实单预约
                List<ExamApplyDto> list_examApply = examScheduleMapper.getScheduleDetailList2(scheduleDetail);
                if (list_examApply != null && !list_examApply.isEmpty()) {
                    ExamApplyDto examApply = list_examApply.get(0);
                    List<String> mergeNos = new ArrayList<>();
                    StringBuilder applyNos = new StringBuilder();
                    for (ExamApplyDto apply : list_examApply) {
                        applyNos.append(",").append(apply.getApplyNo());
                        list_applyNo.add(apply.getApplyNo());
                        mergeNos.add(apply.getApplyNo() + "-" + apply.getItemNo());
                    }
                    ExamApplyItemDto examApplyItemDto = new ExamApplyItemDto();
                    examApplyItemDto.setMergeNos(CommonUtil.split2List(applyNos.substring(1)));
                    examApplyItemDto.setRegFlag("1");
                    List<ExamApplyItemDto> examApplyItemDtoList = examApplyItemMapper.getList(examApplyItemDto);
                    if (examApplyItemDtoList != null && !examApplyItemDtoList.isEmpty()) {
                        commonServiceImpl.handItemCode(examApplyItemDtoList, examApply.getExamSubClass());
                        StringBuilder itemStr = new StringBuilder();
                        StringBuilder mergeNoStr = new StringBuilder();
                        for (ExamApplyItemDto examApplyItem : examApplyItemDtoList) {
                            String mergeNo = examApplyItem.getApplyNo() + "-" + examApplyItem.getItemNo();
                            if (mergeNos.contains(mergeNo)) {
                                int amount = (examApplyItem.getAmount() != null) ? examApplyItem.getAmount() : 1;
                                if (amount > 1) {
                                    itemStr.append("；" + examApplyItem.getItemName() + " 00d7" + amount);
                                } else {
                                    itemStr.append("；" + examApplyItem.getItemName());
                                }
                                mergeNoStr.append("," + mergeNo);
                            }
                        }
                        examApply.setExamApplyItemStr(StringUtils.isNotBlank(itemStr.toString()) ? itemStr.substring(1) : "");
                        examApply.setMergeNo(StringUtils.isNotBlank(mergeNoStr.toString()) ? mergeNoStr.substring(1) : "");
                    }
                    String status = "";
                    if (StringUtils.isNotBlank(examApply.getExamStatus())) {
                        status = CommonUtil.turnScheduleStatus(examApply.getExamStatus());
                    } else {
                        status = CommonUtil.turnScheduleStatus(scheduleDetail.getScheduleStatus());
                    }
                    examApply.setScheduleStatus(status);
                    examApply.setScheduledDate(scheduleDetail.getScheduledDate());
                    examApply.setScheduledTime(scheduleDetail.getScheduledTime());
                    examApply.setScheduleApm(scheduleDetail.getScheduleApm());
                    examApply.setScheduler(scheduleDetail.getScheduler());
                    examApply.setOrgans((scheduleDetail.getOrgans() != null) ? scheduleDetail.getOrgans() : 1.0);
                    examApply.setScheduledId(scheduleDetail.getScheduledId());
                    examApply.setMemo(scheduleDetail.getMemo());
                    examApply.setApmFlag(scheduleDetail.getApmFlag());
                    examApply.setApmText(CommonUtil.turnApmFlag(scheduleDetail.getApmFlag()));
                    examApply.setApmCode(scheduleDetail.getApmCode());
                    String queueName2 = examApply.getQueueName();
                    if (StringUtils.isBlank(queueName2)) {
                        queueName2 = scheduleDetail.getQueueName();
                    }
                    examApply.setQueueName(queueName2);
                    if (StringUtils.isNotBlank(queueName2)) {
                        DictExamQueueDto dictExamQueue = new DictExamQueueDto();
                        dictExamQueue.setExamClass(examApply.getExamClass());
                        dictExamQueue.setQueueName(queueName2);
                        queueName2 = dictExamQueueService.getQueueAlias(dictExamQueue);
                    }
                    examApply.setQueueAlias(queueName2);
                    if (StringUtils.isBlank(examApply.getQueueNo())) {
                        examApply.setQueueNo(scheduleDetail.getQueueNo());
                    }
                    StringBuilder organNameStr = new StringBuilder();
                    ExamApplyOrganDto examApplyOrganDto = new ExamApplyOrganDto();
                    examApplyOrganDto.setApplyNoList(CommonUtil.split2List(applyNos.substring(1)));
                    List<ExamApplyOrganDto> examApplyOrganDtoList = examApplyOrganService.selectList(examApplyOrganDto);
                    if (examApplyOrganDtoList != null && !examApplyOrganDtoList.isEmpty()) {
                        for (ExamApplyOrgan organ : examApplyOrganDtoList) {
                            organNameStr.append("；" + organ.getOrganName());
                        }
                        examApply.setExamApplyOrganStr(StringUtils.isNotBlank(organNameStr.toString()) ? organNameStr.substring(1) : "");
                    }
                    examApply.setSchePath(CommonUtil.convertTerminalType((scheduleDetail.getSchePath() == null) ? "" : scheduleDetail.getSchePath()));
                    examApply.setIndolenceFlag("0");
                    if (StringUtils.isNotBlank(examApply.getFlags())) {
                        char[] flagsArr = examApply.getFlags().toCharArray();
                        examApply.setIndolenceFlag(String.valueOf(flagsArr[12]));
                    }
                    list_result.add(examApply);
                }

                // 虚单预约
                List<ExamApplyDto> referExamApplies = examReferMapper.getScheduleDetailList2(scheduleDetail.getScheduledId());
                if (referExamApplies != null && !referExamApplies.isEmpty()) {
                    for (ExamApplyDto examRefer : referExamApplies) {
                        if (!list_applyNo.contains(examRefer.getApplyNo())) {
                            List<String> mergeNos2 = new ArrayList<String>();
                            StringBuilder applyNos2 = new StringBuilder();
                            for (ExamApplyDto apply2 : referExamApplies) {
                                applyNos2.append("," + apply2.getApplyNo());
                                list_applyNo.add(apply2.getApplyNo());
                                mergeNos2.add(apply2.getApplyNo() + "-" + apply2.getItemNo());
                            }
                            List<ExamReferItemDto> examReferItemDtoList = examReferItemMapper.findByApplyNo(examRefer.getApplyNo());
                            if (examReferItemDtoList != null && !examReferItemDtoList.isEmpty()) {
                                StringBuilder itemStr2 = new StringBuilder();
                                StringBuilder mergeNoStr2 = new StringBuilder();
                                for (ExamReferItemDto examReferItem : examReferItemDtoList) {
                                    String mergeNo2 = examReferItem.getApplyId() + "-" + examReferItem.getItemNo();
                                    if (mergeNos2.contains(mergeNo2)) {
                                        int amount2 = (examReferItem.getAmount() != null) ? examReferItem.getAmount() : 1;
                                        if (amount2 > 1) {
                                            itemStr2.append("；" + examReferItem.getItemName() + " 00d7" + amount2);
                                        } else {
                                            itemStr2.append("；" + examReferItem.getItemName());
                                        }
                                        mergeNoStr2.append("," + mergeNo2);
                                    }
                                }
                                examRefer.setExamApplyItemStr(StringUtils.isNotBlank(itemStr2.toString()) ? itemStr2.substring(1) : "");
                                examRefer.setMergeNo(StringUtils.isNotBlank(mergeNoStr2.toString()) ? mergeNoStr2.substring(1) : "");
                            }
                            String status2 = "";
                            if (StringUtils.isNotBlank(examRefer.getExamStatus())) {
                                status2 = CommonUtil.turnScheduleStatus(examRefer.getExamStatus());
                            } else {
                                status2 = CommonUtil.turnScheduleStatus(scheduleDetail.getScheduleStatus());
                            }
                            examRefer.setScheduleStatus(status2);
                            examRefer.setScheduledDate(scheduleDetail.getScheduledDate());
                            examRefer.setScheduledTime(scheduleDetail.getScheduledTime());
                            examRefer.setScheduleApm(scheduleDetail.getScheduleApm());
                            examRefer.setScheduler(scheduleDetail.getScheduler());
                            examRefer.setOrgans((scheduleDetail.getOrgans() != null) ? scheduleDetail.getOrgans() : 1.0);
                            examRefer.setScheduledId(scheduleDetail.getScheduledId());
                            examRefer.setMemo(scheduleDetail.getMemo());
                            examRefer.setApmFlag(scheduleDetail.getApmFlag());
                            examRefer.setApmText(CommonUtil.turnApmFlag(scheduleDetail.getApmFlag()));
                            examRefer.setApmCode(scheduleDetail.getApmCode());
                            String queueName3 = examRefer.getQueueName();
                            if (StringUtils.isBlank(queueName3)) {
                                queueName3 = scheduleDetail.getQueueName();
                            }
                            examRefer.setQueueName(queueName3);
                            if (StringUtils.isNotBlank(queueName3)) {
                                DictExamQueueDto dictExamQueue2 = new DictExamQueueDto();
                                dictExamQueue2.setExamClass(examRefer.getExamClass());
                                dictExamQueue2.setQueueName(queueName3);
                                queueName3 = dictExamQueueService.getQueueAlias(dictExamQueue2);
                            }
                            examRefer.setQueueAlias(queueName3);
                            if (StringUtils.isBlank(examRefer.getQueueNo())) {
                                examRefer.setQueueNo(scheduleDetail.getQueueNo());
                            }
                            examRefer.setSchePath(CommonUtil.convertTerminalType((scheduleDetail.getSchePath() == null) ? "" : scheduleDetail.getSchePath()));
                            examRefer.setIndolenceFlag("0");
                            if (StringUtils.isNotBlank(examRefer.getFlags())) {
                                char[] flagsArr2 = examRefer.getFlags().toCharArray();
                                examRefer.setIndolenceFlag(String.valueOf(flagsArr2[12]));
                            }
                            list_result.add(examRefer);
                        }
                    }
                }
            }
            list_result.sort((o1, o2) -> {
                if (o1 == null && o2 == null) {
                    return 0;
                } else if (o1 == null) {
                    return -1;
                } else if (o2 == null) {
                    return 1;
                } else if (o1.getApmCode().hashCode() > o2.getApmCode().hashCode()) {
                    return 1;
                } else if (o1.getApmCode().hashCode() < o2.getApmCode().hashCode()) {
                    return -1;
                } else if (o1.getApmCode().hashCode() == o2.getApmCode().hashCode()) {
                    if (o1.getScheduleStatus().equals(o2.getScheduleStatus())) {
                        return 0;
                    } else {
                        return o1.getScheduleStatus().compareTo(o2.getScheduleStatus());
                    }
                } else {
                    return 0;
                }
            });
        }
        return list_result;
    }

    @Override
    public JsonResult editScheduleQueueMulti(ExamScheduleDto dto) {
        if (!StringUtils.isNotBlank(dto.getScheduledId()) || !StringUtils.isNotBlank(dto.getQueueName())) {
            return JsonResultUtil.failure("预约ID编号不能为空");
        }
        boolean isExamClass4Organ = configService.getOrganExamClassList().contains(dto.getExamClass());
        String reqQueueName = dto.getQueueName();
        StringBuffer errMsgs = new StringBuffer();
        String[] split;
        String[] scheduledIds = split = dto.getScheduledId().split(",");
        for (String id : split) {
            QueryWrapper<ExamSchedule> queryWrapper = (QueryWrapper<ExamSchedule>) new QueryWrapper();
            queryWrapper.eq("SCHEDULED_ID", id);
            ExamSchedule schedule = (ExamSchedule) examScheduleMapper.selectOne((Wrapper) queryWrapper);
            if (schedule != null) {
                String scheduledId = StringUtils.isNotBlank(schedule.getScheduledId()) ? schedule.getScheduledId() : "";
                String oldScheduleQueue = StringUtils.isNotBlank(schedule.getQueueName()) ? schedule.getQueueName() : "";
                String oldApmCode = StringUtils.isNotBlank(schedule.getApmCode()) ? schedule.getApmCode() : "";
                String oldScheduleApm = StringUtils.isNotBlank(schedule.getScheduleApm()) ? schedule.getScheduleApm() : "";
                String oldScheduleDate = StringUtils.isNotBlank(schedule.getScheduledDate()) ? schedule.getScheduledDate() : "";
                String nextApmRatio = StringUtils.isNotBlank(schedule.getNextApmRatio()) ? schedule.getNextApmRatio() : "";
                Double scheduleRatio = (schedule.getOrgans() != null) ? schedule.getOrgans() : 0.0;
                DictScheduleApm oldApmInfo = dictScheduleApmService.selectOneByApmCode(oldApmCode);
                DictScheduleApmDto dsaDto = new DictScheduleApmDto();
                dsaDto.setQueueNames(CommonUtil.split2List(dto.getQueueName()));
                dsaDto.setTimeStart(oldApmInfo.getTimeStart());
                dsaDto.setTimeEnd(oldApmInfo.getTimeEnd());
                dsaDto.setScheduleDate(oldScheduleDate);
                dsaDto.setWeekDate(DateUtil.getWeek(oldScheduleDate));
                List<DictScheduleApm> liNormal = (List<DictScheduleApm>) dictScheduleApmService.getNormalSchedule(dsaDto);
                if (liNormal == null || liNormal.size() == 0) {
                    return JsonResultUtil.failure("当前队列[" + reqQueueName + "]的通用时段为空");
                }
                List<DictScheduleApm> liWeekDateSpeci = (List<DictScheduleApm>) dictScheduleApmService.getWeekDateScheduleApms(dsaDto);
                List<DictScheduleApm> liDateSpeci = (List<DictScheduleApm>) dictScheduleApmService.getDateScheduleApms(dsaDto);
                List<DictScheduleApm> liApm = getScheduleRegular(liDateSpeci, liWeekDateSpeci, liNormal);
                if (liApm == null || liApm.size() > 1) {
                    return JsonResultUtil.failure("当前队列[" + reqQueueName + "]的" + oldScheduleApm + "时段可能有多条数据，请检查号源时段数据");
                }
                String newApmCode = liApm.get(0).getApmCode();
                String newScheduleApm = liApm.get(0).getScheduleApm();
                ExamScheduleDto examScheduleDto = new ExamScheduleDto();
                examScheduleDto.setScheduledId(scheduledId);
                examScheduleDto.setQueueName(dto.getQueueName());
                examScheduleDto.setApmCode(newApmCode);
                examScheduleDto.setScheduleApm(newScheduleApm);
                if (examScheduleMapper.updateForQueueName(examScheduleDto) != -1) {
                    double nextOrganTotal_new = 0.0;
                    double nextOrganTotal_old = 0.0;
                    if (isExamClass4Organ && StringUtils.isNotBlank(nextApmRatio)) {
                        String[] split2;
                        String[] nextApmRatioArr = split2 = nextApmRatio.split("\\|");
                        for (String apmRatio : split2) {
                            String[] apmRatioArr_new = apmRatio.split("=");
                            DictScheduleApm dsa_old = dictScheduleApmService.selectOneByApmCode(apmRatioArr_new[0]);
                            DictScheduleApmDto dsaDto_new = new DictScheduleApmDto();
                            dsaDto_new.setQueueNames(CommonUtil.split2List(dto.getQueueName()));
                            dsaDto_new.setTimeStart(dsa_old.getTimeStart());
                            dsaDto_new.setTimeEnd(dsa_old.getTimeEnd());
                            dsaDto_new.setScheduleDate(oldScheduleDate);
                            dsaDto_new.setWeekDate(DateUtil.getWeek(oldScheduleDate));
                            List<DictScheduleApm> liNormal_new = (List<DictScheduleApm>) dictScheduleApmService.getNormalSchedule(dsaDto_new);
                            if (liNormal_new != null) {
                                if (liNormal_new.size() != 0) {
                                    List<DictScheduleApm> liWeekDateSpeci_new = (List<DictScheduleApm>) dictScheduleApmService.getWeekDateScheduleApms(dsaDto_new);
                                    List<DictScheduleApm> liDateSpeci_new = (List<DictScheduleApm>) dictScheduleApmService.getDateScheduleApms(dsaDto_new);
                                    List<DictScheduleApm> liApm_new = getScheduleRegular(liDateSpeci_new, liWeekDateSpeci_new, liNormal_new);
                                    if (liApm_new != null) {
                                        if (liApm_new.size() <= 1) {
                                            List<ExamScheduleApm> list_new = commonServiceImpl.getExamScheduleApm(liApm_new.get(0).getApmCode(), oldScheduleDate);
                                            nextOrganTotal_new = BigDecimalUtil.add(nextOrganTotal_new, (double) Double.valueOf(apmRatioArr_new[1]));
                                            if (list_new != null && !list_new.isEmpty()) {
                                                UpdateWrapper<ExamScheduleApm> updateWrapper_new = (UpdateWrapper<ExamScheduleApm>) new UpdateWrapper();
                                                ExamScheduleApm examScheduleApm = new ExamScheduleApm();
                                                double organs_new = (list_new.get(0).getOrgans() != null) ? list_new.get(0).getOrgans() : 0.0;
                                                examScheduleApm.setOrgans(Double.valueOf(BigDecimalUtil.add((double) Double.valueOf(apmRatioArr_new[1]), organs_new)));
                                                updateWrapper_new.eq("SCHEDULE_DATE", oldScheduleDate);
                                                updateWrapper_new.eq("APM_CODE", list_new.get(0).getApmCode());
                                                examScheduleApmMapper.update(examScheduleApm, (Wrapper) updateWrapper_new);
                                            } else {
                                                ExamScheduleApm examScheduleApm2 = new ExamScheduleApm();
                                                examScheduleApm2.setScheduleDate(oldScheduleDate);
                                                examScheduleApm2.setApmCode(liApm_new.get(0).getApmCode());
                                                examScheduleApm2.setOrgans(Double.valueOf(apmRatioArr_new[1]));
                                                examScheduleApmMapper.insert(examScheduleApm2);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        for (String apmRatio : nextApmRatioArr) {
                            String[] apmRatioArr_old = apmRatio.split("=");
                            List<ExamScheduleApm> list_old = commonServiceImpl.getExamScheduleApm(apmRatioArr_old[0], oldScheduleDate);
                            nextOrganTotal_old = BigDecimalUtil.add(nextOrganTotal_old, (double) Double.valueOf(apmRatioArr_old[1]));
                            if (list_old != null && !list_old.isEmpty()) {
                                UpdateWrapper<ExamScheduleApm> updateWrapper_new2 = (UpdateWrapper<ExamScheduleApm>) new UpdateWrapper();
                                ExamScheduleApm examScheduleApm3 = new ExamScheduleApm();
                                if (list_old.get(0).getOrgans() != null && list_old.get(0).getOrgans() > 0.0) {
                                    examScheduleApm3.setOrgans(Double.valueOf(BigDecimalUtil.subtract((double) list_old.get(0).getOrgans(), (double) Double.valueOf(apmRatioArr_old[1]))));
                                }
                                updateWrapper_new2.eq("SCHEDULE_DATE", oldScheduleDate);
                                updateWrapper_new2.eq("APM_CODE", list_old.get(0).getApmCode());
                                examScheduleApmMapper.update(examScheduleApm3, (Wrapper) updateWrapper_new2);
                            }
                        }
                    }
                    List<ExamScheduleApm> list_new2 = commonServiceImpl.getExamScheduleApm(newApmCode, oldScheduleDate);
                    if (list_new2 != null && !list_new2.isEmpty()) {
                        ExamScheduleApm apm = list_new2.get(0);
                        UpdateWrapper<ExamScheduleApm> updateWrapper_new3 = (UpdateWrapper<ExamScheduleApm>) new UpdateWrapper();
                        ExamScheduleApm examScheduleApm4 = new ExamScheduleApm();
                        if (isExamClass4Organ) {
                            examScheduleApm4.setOrgans(Double.valueOf(BigDecimalUtil.add((double) apm.getOrgans(), BigDecimalUtil.subtract((double) scheduleRatio, nextOrganTotal_new))));
                        }
                        examScheduleApm4.setCount(Integer.valueOf(apm.getCount() + 1));
                        updateWrapper_new3.eq("SCHEDULE_DATE", oldScheduleDate);
                        updateWrapper_new3.eq("APM_CODE", apm.getApmCode());
                        examScheduleApmMapper.update(examScheduleApm4, (Wrapper) updateWrapper_new3);
                    } else {
                        ExamScheduleApm examScheduleApm5 = new ExamScheduleApm();
                        examScheduleApm5.setScheduleDate(oldScheduleDate);
                        examScheduleApm5.setApmCode(newApmCode);
                        if (isExamClass4Organ) {
                            examScheduleApm5.setOrgans(Double.valueOf(BigDecimalUtil.subtract((double) scheduleRatio, nextOrganTotal_new)));
                        }
                        examScheduleApm5.setCount(Integer.valueOf(1));
                        examScheduleApmMapper.insert(examScheduleApm5);
                    }
                    List<ExamScheduleApm> list_old2 = commonServiceImpl.getExamScheduleApm(oldApmCode, oldScheduleDate);
                    if (list_old2 != null && !list_old2.isEmpty()) {
                        ExamScheduleApm apm2 = list_old2.get(0);
                        UpdateWrapper<ExamScheduleApm> updateWrapper_old = (UpdateWrapper<ExamScheduleApm>) new UpdateWrapper();
                        ExamScheduleApm examScheduleApm6 = new ExamScheduleApm();
                        if (isExamClass4Organ) {
                            examScheduleApm6.setOrgans(Double.valueOf(BigDecimalUtil.subtract((double) apm2.getOrgans(), BigDecimalUtil.subtract((double) scheduleRatio, nextOrganTotal_old))));
                        }
                        examScheduleApm6.setCount(Integer.valueOf(apm2.getCount() - 1));
                        updateWrapper_old.eq("SCHEDULE_DATE", oldScheduleDate);
                        updateWrapper_old.eq("APM_CODE", oldApmCode);
                        examScheduleApmMapper.update(examScheduleApm6, (Wrapper) updateWrapper_old);
                    }
                } else {
                    errMsgs.append("，" + scheduledId);
                }
            } else {
                errMsgs.append("，" + id);
            }
        }
        if (StringUtils.isNotBlank(errMsgs.toString())) {
            return JsonResultUtil.failure("[" + errMsgs.substring(1) + "]预约数据修改失败，其它则成功");
        }
        return JsonResultUtil.success();
    }

    @Override
    public JsonResult stopSourceForQueueName(ExamScheduleDto dto) {
        String reqQueueName = dto.getQueueName();
        if (StringUtils.isBlank(dto.getQueueName())) {
            return JsonResultUtil.failure("预约队列不能为空");
        }
        StringBuilder queueScheduleApm = new StringBuilder();
        DictScheduleApmDto scheduleApmDto = new DictScheduleApmDto();
        scheduleApmDto.setQueueNames(CommonUtil.split2List(dto.getQueueName()));
        if (!"合计".equals(dto.getScheduleApm()) && StringUtils.isNotBlank(dto.getScheduleApm())) {
            scheduleApmDto.setScheduleApm(dto.getScheduleApm());
        } else if (StringUtils.isNotBlank(dto.getApmFlag())) {
            if (ConstantsUtil.DictScheduleApmFlag.MORNING.getValue().equals(dto.getApmFlag())) {
                scheduleApmDto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.MORNING.getKey());
            } else if (ConstantsUtil.DictScheduleApmFlag.AFTERNOON.getValue().equals(dto.getApmFlag())) {
                scheduleApmDto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.AFTERNOON.getKey());
            } else if (ConstantsUtil.DictScheduleApmFlag.NIGHT.getValue().equals(dto.getApmFlag())) {
                scheduleApmDto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.NIGHT.getKey());
            } else if (ConstantsUtil.DictScheduleApmFlag.NOON.getValue().equals(dto.getApmFlag())) {
                scheduleApmDto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.NOON.getKey());
            } else if ("合计".equals(dto.getApmFlag())) {
                scheduleApmDto.setApmFlag((String) null);
            } else {
                scheduleApmDto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.ALLDAY.getKey());
            }
        }
        List<DictScheduleApm> apmList = (List<DictScheduleApm>) dictScheduleApmService.getNormalSchedule(scheduleApmDto);
        if (apmList == null || apmList.size() == 0) {
            return JsonResultUtil.failure("当前队列[" + reqQueueName + "]的通用时段为空");
        }
        for (DictScheduleApm apm : apmList) {
            QueryWrapper<DictScheduleApm> apmQueryWrapper = new QueryWrapper<>();
            apmQueryWrapper.eq("APM_CODE", apm.getApmCode());
            apmQueryWrapper.ne("STOP_FLAG", "2");
            apmQueryWrapper.eq("SCHEDULE_DATE", dto.getScheduledDate());
            if (dictScheduleApmService.count(apmQueryWrapper) == 1) {
                queueScheduleApm.append(",日期=" + apm.getScheduleApm() + "=" + dto.getScheduledDate() + "=" + apm.getDateStart() + "=" + apm.getDateEnd());
            } else {
                queueScheduleApm.append(",通用=" + apm.getScheduleApm() + "=" + apm.getDateStart() + "=" + apm.getDateEnd());
            }
        }
        DictScheduleApmDto dictScheduleApmDto = new DictScheduleApmDto();
        dictScheduleApmDto.setQueueName(dto.getQueueName());
        dictScheduleApmDto.setStopFlag("1");
        dictScheduleApmDto.setQueueScheduleApm(StringUtils.isNotBlank(queueScheduleApm) ? queueScheduleApm.substring(1) : "");
        DictExamQueueDto dictExamQueueDto = new DictExamQueueDto();
        dictExamQueueDto.setQueueName(dto.getQueueName());
        List<DictExamQueue> queueList = (List<DictExamQueue>) dictExamQueueService.getQueueNameList((DictExamQueue) dictExamQueueDto);
        if (queueList != null && !queueList.isEmpty()) {
            dictScheduleApmDto.setExamClass(queueList.get(0).getExamClass());
        }
        dictScheduleApmDto.setScheduleDate(dto.getScheduledDate());
        String result = sourceService.startOrStopForSource(dictScheduleApmDto);
        return JsonResultUtil.success(result);
    }

    @Override
    public JsonResult getDateSourceInfo(ExamScheduleDto dto) {
        boolean isExamClass4Organ = configService.getOrganExamClassList().contains(dto.getExamClass());
        String isRecycleSource = StringUtils.isNotBlank(dto.getIsRecycleSource()) ? dto.getIsRecycleSource() : "0";
        try {
            String reqQueueName = dto.getQueueName();
            if (StringUtils.isBlank(dto.getQueueName())) {
                return JsonResultUtil.failure("预约队列不能为空");
            }
            dto.setQueueNames(CommonUtil.split2List(dto.getQueueName()));
            dto.setWeekDate(DateUtil.getWeek(dto.getScheduledDate()));
            DictScheduleApmDto dsaDto = new DictScheduleApmDto();
            dsaDto.setQueueNames(dto.getQueueNames());
            dsaDto.setScheduleApm(dto.getScheduleApm());
            dsaDto.setScheduleDate(dto.getScheduledDate());
            dsaDto.setWeekDate(dto.getWeekDate());
            List<DictScheduleApm> liNormal = (List<DictScheduleApm>) dictScheduleApmService.getNormalSchedule(dsaDto);
            if (liNormal == null || liNormal.size() == 0) {
                return JsonResultUtil.failure("当前队列[" + reqQueueName + "]的通用时段为空");
            }
            List<DictScheduleApm> liWeekDateSpeci = (List<DictScheduleApm>) dictScheduleApmService.getWeekDateScheduleApms(dsaDto);
            List<DictScheduleApm> liDateSpeci = (List<DictScheduleApm>) dictScheduleApmService.getDateScheduleApms(dsaDto);
            List<DictScheduleApm> liApm = getScheduleRegular(liDateSpeci, liWeekDateSpeci, liNormal);
            if (liApm == null || liApm.size() > 1) {
                return JsonResultUtil.failure("当前队列[" + reqQueueName + "]的" + dto.getScheduleApm() + "时段可能有多条数据，请检查号源时段数据");
            }
            List<DictScheduleApmDto> apmList = new ArrayList<DictScheduleApmDto>();
            for (DictScheduleApm apm : liApm) {
                DictScheduleApmDto apmDto = new DictScheduleApmDto();
                BeanUtils.copyProperties(apm, apmDto);
                if (StringUtils.isBlank(apm.getLimitType())) {
                    if (isExamClass4Organ) {
                        apmDto.setLimitType("2");
                    } else {
                        apmDto.setLimitType("1");
                    }
                }
                DictExamQueue dictExamQueue = new DictExamQueue();
                dictExamQueue.setQueueName(apm.getQueueName());
                List<DictExamQueue> queueList = (List<DictExamQueue>) dictExamQueueService.getQueueNameList(dictExamQueue);
                if (queueList != null && !queueList.isEmpty()) {
                    apmDto.setExamClass(queueList.get(0).getExamClass());
                    if (StringUtils.isNotBlank(queueList.get(0).getQueueAlias())) {
                        apmDto.setQueueAlias(queueList.get(0).getQueueAlias());
                    } else {
                        apmDto.setQueueAlias(queueList.get(0).getQueueName());
                    }
                }
                if ("1".equals(isRecycleSource)) {
                    dsaDto.setIsRecycleSource(isRecycleSource);
                    List<DictScheduleApmDto> dictScheduleApmDtoList = (List<DictScheduleApmDto>) dictScheduleApmService.getScheduleApms(dsaDto);
                    List<String> apmCodes = new ArrayList<String>();
                    if (dictScheduleApmDtoList != null && !dictScheduleApmDtoList.isEmpty()) {
                        for (DictScheduleApmDto scheduleApmDto : dictScheduleApmDtoList) {
                            apmCodes.add(scheduleApmDto.getApmCode());
                        }
                        ExamScheduleApm examScheduleapm = commonServiceImpl.examScheduleApm(dto.getScheduledDate(), apmCodes, dto.getExamClass());
                        Integer curRecycle = 0;
                        if (examScheduleapm != null) {
                            if (isExamClass4Organ) {
                                DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
                                df.setMaximumFractionDigits(1);
                                String organsRecycle = df.format(examScheduleapm.getOrgansRecycle()).replaceAll("\\.0", "");
                                curRecycle = Integer.parseInt(organsRecycle);
                            } else {
                                curRecycle = examScheduleapm.getCountRecycle();
                            }
                        }
                        apmDto.setCurRecycle(curRecycle);
                    }
                }
                apmList.add(apmDto);
            }
            return JsonResultUtil.success("成功", apmList);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public JsonResult editDateSourceInfo(ExamScheduleDto dto) {
        boolean isExamClass4Organ = configService.getOrganExamClassList().contains(dto.getExamClass());
        String isRecycleSource = StringUtils.isNotBlank(dto.getIsRecycleSource()) ? dto.getIsRecycleSource() : "0";
        dto.setWeekDate(DateUtil.getWeek(dto.getScheduledDate()));
        DictScheduleApmDto dictScheduleApmDto = new DictScheduleApmDto();
        dictScheduleApmDto.setQueueName(dto.getQueueName());
        dictScheduleApmDto.setScheduleApm(dto.getScheduleApm());
        dictScheduleApmDto.setScheduleDate(dto.getScheduledDate());
        dictScheduleApmDto.setWeekDate(dto.getWeekDate());
        if ("1".equals(isRecycleSource)) {
            dictScheduleApmDto.setQueueNames(CommonUtil.split2List(dictScheduleApmDto.getQueueName()));
            dictScheduleApmDto.setIsRecycleSource(isRecycleSource);
            List<DictScheduleApmDto> dictScheduleApmDtoList = (List<DictScheduleApmDto>) dictScheduleApmService.getScheduleApms(dictScheduleApmDto);
            if (dictScheduleApmDtoList != null && !dictScheduleApmDtoList.isEmpty()) {
                for (DictScheduleApmDto scheduleApmDto : dictScheduleApmDtoList) {
                    ExamScheduleApm examScheduleApm = new ExamScheduleApm();
                    examScheduleApm.setApmCode(scheduleApmDto.getApmCode());
                    examScheduleApm.setScheduleDate(dto.getScheduledDate());
                    if (isExamClass4Organ) {
                        examScheduleApm.setOrgansRecycle(Double.valueOf(0.0));
                    } else {
                        examScheduleApm.setCountRecycle(Integer.valueOf(0));
                    }
                    examScheduleApmService.updateExamScheduleApm(examScheduleApm);
                }
                String apmCode = "";
                DictScheduleApm apm = dictScheduleApmService.selectOne(dictScheduleApmDto, "日期");
                if (apm != null) {
                    apmCode = apm.getApmCode();
                } else {
                    apm = dictScheduleApmService.selectOne(dictScheduleApmDto, "星期");
                    if (apm != null) {
                        apmCode = apm.getApmCode();
                    } else {
                        apm = dictScheduleApmService.selectOne(dictScheduleApmDto, "通用");
                        apmCode = apm.getApmCode();
                    }
                }
                ExamScheduleApm scheduleApm = new ExamScheduleApm();
                scheduleApm.setApmCode(apmCode);
                scheduleApm.setScheduleDate(dto.getScheduledDate());
                Integer curRecycle = (dto.getCurRecycle() != null) ? dto.getCurRecycle() : 0;
                if (isExamClass4Organ) {
                    scheduleApm.setOrgansRecycle(Double.valueOf((double) curRecycle));
                } else {
                    scheduleApm.setCountRecycle(curRecycle);
                }
                examScheduleApmService.updateExamScheduleApm(scheduleApm);
                return JsonResultUtil.success();
            }
            return JsonResultUtil.failure("没有[" + dto.getQueueName() + "(" + dto.getScheduleApm() + ")]号源信息");
        } else {
            DictScheduleApm apm2 = dictScheduleApmService.selectOne(dictScheduleApmDto, "日期");
            if (apm2 != null) {
                return sourceService.editScheduleApm(entity(apm2, dto));
            }
            apm2 = dictScheduleApmService.selectOne(dictScheduleApmDto, "星期");
            if (apm2 != null) {
                return sourceService.saveScheduleApm(entity(apm2, dto));
            }
            apm2 = dictScheduleApmService.selectOne(dictScheduleApmDto, "通用");
            apm2.setScheduleDate(dto.getScheduledDate());
            return sourceService.saveScheduleApm(entity(apm2, dto));
        }
    }

    private DictScheduleApmDto entity(DictScheduleApm apm, ExamScheduleDto scheduleDto) {
        DictScheduleApmDto apmDto = new DictScheduleApmDto();
        apmDto.setApmCode(apm.getApmCode());
        apmDto.setQueueName(apm.getQueueName());
        apmDto.setScheduleApm(apm.getScheduleApm());
        apmDto.setDateStart(apm.getDateStart());
        apmDto.setDateEnd(apm.getDateEnd());
        apmDto.setTimeStart(apm.getTimeStart());
        apmDto.setTimeEnd(apm.getTimeEnd());
        apmDto.setApmLength(apm.getApmLength());
        apmDto.setApmFlag(apm.getApmFlag());
        apmDto.setTimeScheduleLatest(apm.getTimeScheduleLatest());
        apmDto.setTimeEarliest(apm.getTimeEarliest());
        apmDto.setTimeSignin(apm.getTimeSignin());
        apmDto.setDrugTime(apm.getDrugTime());
        apmDto.setLimitType(apm.getLimitType());
        apmDto.setScheduleDate(scheduleDto.getScheduledDate());
        apmDto.setMaxLimit(scheduleDto.getMaxLimit());
        apmDto.setStopFlag(scheduleDto.getStopFlag());
        apmDto.setDaysEarliest(apm.getDaysEarliest());
        apmDto.setDaysScheduleLatest(apm.getDaysScheduleLatest());
        apmDto.setTimeScheduleFirst(apm.getTimeScheduleFirst());
        apmDto.setDaysScheduleFirst(apm.getDaysScheduleFirst());
        apmDto.setMergeApmCode(apm.getMergeApmCode());
        String scheduleApm = apm.getScheduleApm();
        if (StringUtils.isNotBlank(apm.getTimeStart()) && StringUtils.isNotBlank(apm.getTimeEnd())) {
            String timeStart = apm.getTimeStart().substring(0, apm.getTimeStart().lastIndexOf(":"));
            String timeEnd = DateUtil.addMinutes2(apm.getTimeEnd().substring(0, apm.getTimeEnd().lastIndexOf(":")), 1);
            scheduleApm = timeStart + "~" + timeEnd;
        }
        apmDto.setScheduleApmScope(scheduleApm);
        DictScheduleApmRegularDto regularDto = new DictScheduleApmRegularDto();
        regularDto.setApmCode(apm.getApmCode());
        List<DictScheduleApmRegular> apmRegularList = (List<DictScheduleApmRegular>) dictScheduleApmRegularService.selectList(regularDto);
        if (apmRegularList != null && !apmRegularList.isEmpty()) {
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder regularSchedule = new StringBuilder();
            for (DictScheduleApmRegular apmRegular : apmRegularList) {
                if (apmRegular.getMinLimit() == null) {
                    stringBuilder.append("," + apmRegular.getRegularId());
                } else {
                    regularSchedule.append("," + apmRegular.getRegularId() + "=" + apmRegular.getMinLimit() + "-" + apmRegular.getMaxLimit());
                }
            }
            if (StringUtils.isNotBlank(stringBuilder)) {
                apmDto.setRegularDefSchedule(stringBuilder.substring(1));
            }
            if (StringUtils.isNotBlank(regularSchedule)) {
                apmDto.setRegularSchedule(regularSchedule.substring(1));
            }
        }
        apmDto.setExamClass(scheduleDto.getExamClass());
        return apmDto;
    }

    @Override
    public JsonResult editScheduleStatus(ExamApplyDto dto) {
        if (StringUtils.isBlank(dto.getApplyNo())) {
            return JsonResultUtil.failure("applyNo不能为空");
        }
        if (StringUtils.isBlank(dto.getScheduleStatus())) {
            return JsonResultUtil.failure("scheduleStatus不能为空");
        }
        if (!"0,2,3,4,c,C,5,6".contains(dto.getScheduleStatus())) {
            return JsonResultUtil.failure("预约状态传参错误");
        }
        if (dto.getItemNo() == null) {
            dto.setItemNo(1l);
        }
        ExamScheduleItemDto examScheduleItemDto = new ExamScheduleItemDto();
        examScheduleItemDto.setApplyNo(dto.getApplyNo());
        examScheduleItemDto.setItemNo(dto.getItemNo());
        Map<String, Object> map = new HashMap<>();
        map.put("APPLY_NO", dto.getApplyNo());
        map.put("ITEM_NO", dto.getItemNo());
        QueryWrapper<ExamScheduleItem> qw = new QueryWrapper<>();
        qw.allEq(map, false);
        List<ExamScheduleItem> list = examScheduleItemMapper.selectList(qw);

        ExamApplyDto ea_ = commonServiceImpl.getExamApplyInfo(dto.getApplyNo(), dto.getTerminalType());
        if (ea_ != null) {
            commonServiceImpl.getScheduleToExamApply(dto, ea_);
        }
        ExamApplyItemDto item = new ExamApplyItemDto();
        item.setApplyNo(dto.getApplyNo());
        item.setItemNo(dto.getItemNo());
        List<ExamApplyItemDto> items = examApplyItemMapper.getList(item);
        ea_.setItems(items);
        List<String> megerNos = new ArrayList<String>();
        for (ExamApplyItem examApplyItem : items) {
            megerNos.add(examApplyItem.getApplyNo() + "-" + examApplyItem.getItemNo());
        }
        dto.setMergeNo(StringUtils.join(megerNos, ","));
        if ("0".equals(dto.getScheduleStatus())) {
            if (list.size() == 0) {
                return JsonResultUtil.failure("预约记录为空");
            }
            String scheduleId = list.get(0).getScheduledId();
            QueryWrapper<ExamSchedule> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("SCHEDULED_ID", scheduleId);
            ExamSchedule es = examScheduleMapper.selectOne(queryWrapper);
            if (es != null) {
                ExamApplyDto ea = new ExamApplyDto();
                ea.setApplyNo(dto.getApplyNo());
                ea.setScheduledId(scheduleId);
                ea.setScheduleDate(es.getScheduledDate());
                ea.setOrgans(es.getOrgans());
                ea.setNextApmRatio(es.getNextApmRatio());
                ea.setRegularIdList(Arrays.asList(es.getRegularId()));
                ea.setApmCode(es.getApmCode());
                String mergeNos = "";
                for (ExamScheduleItem esi : list) {
                    mergeNos = mergeNos + "," + dto.getApplyNo() + "-" + esi.getItemNo();
                }
                ea.setMergeNo(mergeNos.substring(1));
                boolean isExamClass4Organ = configService.getOrganExamClassList().contains(items.get(0).getExamClass());
                double reqCount = 1.0;
                if (isExamClass4Organ) {
                    reqCount = commonServiceImpl.getReqOrganByItems(items);
                }
                ea.setReqCount(reqCount);
                JsonResult recedeCostResult = commonServiceImpl.recedeCost(ea, ConstantsUtil.ActType.CANCEL.getType(), commonServiceImpl.dictUsers(dto));
                if (recedeCostResult != null && !"0".equals(recedeCostResult.getStatus())) {
                    return JsonResultUtil.failure(recedeCostResult.getMessage());
                }
                if ("08".equals(es.getScheduleStatus())) {
                    ea.setExamClass(items.get(0).getExamClass());
                    ea.setTerminalType(ConstantsUtil.TerminalType.SYSTEM.getType());
                }
                if (es.getApmCode() != null) {
                    commonServiceImpl.cancelScheduleInfo(ea, isExamClass4Organ);
                } else {
                    Map<String, Object> param = new HashMap<>();
                    param.put("scheduled_id", scheduleId);
                    examScheduleMapper.deleteByMap(param);
                    examScheduleItemMapper.deleteByMap(param);
                }
                ExamApplyItemDto it = new ExamApplyItemDto();
                it.setApplyNo(dto.getApplyNo());
                it.setRegAmount(0);
                examApplyItemMapper.updateItem(it);
                ea_.setActType(ConstantsUtil.ActType.CANCEL.getType());
            }
            List<String> applyNos = CommonUtil.mergeNo2ApplyNos(dto.getMergeNo());
            ea_.setApplyNos(applyNos);
            ea_.setActType(ConstantsUtil.ActType.CANCEL.getType());
            ea_.setMergeNo(dto.getMergeNo());
            ea_.setTerminalType(dto.getTerminalType());
            String itemNameStr = "";
            for (ExamApplyItemDto applyItem : items) {
                itemNameStr = itemNameStr + applyItem.getItemName() + ";";
            }
            ea_.setItemNameStr(itemNameStr);
            configService.isScheduleSync(ea_, ea_.getActType(), ConstantsUtil.ScheduleStatus.NINE.getStatus());
        } else if ("2".equals(dto.getScheduleStatus())) {
            if (list.size() == 0) {
                return JsonResultUtil.failure("预约记录为空");
            }
            String examStatus = list.get(0).getExamStatus();
            if ("40".equals(examStatus)) {
                return JsonResultUtil.failure("您的检查申请已检查，不能取消报到");
            }
            ExamScheduleItem examScheduleItem = new ExamScheduleItem();
            examScheduleItem.setApplyNo(dto.getApplyNo());
            examScheduleItem.setItemNo(dto.getItemNo());
            examScheduleItem.setExamStatus("");
            examScheduleItemService.update(examScheduleItem);
            ExamApplyItemDto it2 = new ExamApplyItemDto();
            it2.setApplyNo(dto.getApplyNo());
            it2.setRegAmount(0);
            examApplyItemMapper.updateItem(it2);
            ea_.setActType(ConstantsUtil.ActType.CANCEL_SIGN.getType());
        } else if ("3,4,5,6".contains(dto.getScheduleStatus())) {
            String examStatus = ConstantsUtil.ExamStatus.SCHEDULE_TWENTY.getStatus();
            ea_.setActType(ConstantsUtil.ActType.SIGN.getType());
            if ("4".equals(dto.getScheduleStatus())) {
                examStatus = "40";
                ea_.setActType(ConstantsUtil.ActType.EXAM.getType());
            } else if ("5".equals(dto.getScheduleStatus())) {
                examStatus = "60";
                ea_.setActType(ConstantsUtil.ActType.EXAM.getType());
            } else if ("6".equals(dto.getScheduleStatus())) {
                examStatus = "70";
                ea_.setActType(ConstantsUtil.ActType.EXAM.getType());
            }
            ExamScheduleItem examScheduleItem = new ExamScheduleItem();
            examScheduleItem.setApplyNo(dto.getApplyNo());
            examScheduleItem.setItemNo(dto.getItemNo());
            examScheduleItem.setExamStatus(examStatus);
            int i = examScheduleItemService.update(examScheduleItem);
            if (i == 0) {
                String scheduledId = PKGeneratorSingle.getInstance().nextPKStr();
                ea_.setScheduledId(scheduledId);
                ExamSchedule es2 = new ExamSchedule();
                es2.setScheduledId(scheduledId);
                es2.setScheduleStatus("08");
                es2.setScheduledDate(DateUtil.getCurrDateStr());
                es2.setScheduleApm("00:00~00:00");
                es2.setQueueName("无");
                examScheduleService.insertSelective(es2);
                if (dto.getItemNo() == null) {
                    ExamApplyItemDto itemDto = new ExamApplyItemDto();
                    itemDto.setApplyNo(dto.getApplyNo());
                    List<ExamApplyItem> examApplyItems = (List<ExamApplyItem>) examApplyItemService.selectList(itemDto);
                    for (ExamApplyItem examApplyItem2 : examApplyItems) {
                        ExamScheduleItem esi2 = new ExamScheduleItem();
                        esi2.setScheduledId(scheduledId);
                        esi2.setExamStatus(examStatus);
                        esi2.setApplyNo(dto.getApplyNo());
                        esi2.setItemNo(examApplyItem2.getItemNo());
                        if (StringUtils.isNotBlank(dto.getExamNo())) {
                            esi2.setExamNo(dto.getExamNo());
                            esi2.setPatLocalId(dto.getPatLocalId());
                            esi2.setQueueNo(dto.getQueueNo());
                        }
                        examScheduleItemService.insertSelective(esi2);
                    }
                } else {
                    ExamScheduleItem esi3 = new ExamScheduleItem();
                    esi3.setScheduledId(scheduledId);
                    esi3.setExamStatus(examStatus);
                    esi3.setApplyNo(dto.getApplyNo());
                    esi3.setItemNo(dto.getItemNo());
                    if (StringUtils.isNotBlank(dto.getExamNo())) {
                        esi3.setExamNo(dto.getExamNo());
                        esi3.setPatLocalId(dto.getPatLocalId());
                        esi3.setQueueNo(dto.getQueueNo());
                    }
                    examScheduleItemService.insertSelective(esi3);
                }
            }
            if (items.get(0).getRegAmount() == null || items.get(0).getRegAmount() == 0) {
                ExamApplyItemDto itemDto2 = new ExamApplyItemDto();
                itemDto2.setRegAmount(items.get(0).getAmount());
                itemDto2.setApplyNo(items.get(0).getApplyNo());
                itemDto2.setItemNo(items.get(0).getItemNo());
                itemDto2.setOrderNo(items.get(0).getOrderNo());
                examApplyItemService.updateItem(itemDto2);
            }
        } else if ("C".equals(dto.getScheduleStatus()) || "c".equals(dto.getScheduleStatus())) {
            ea_.setActType(ConstantsUtil.ActType.DEL_APPLY.getType());
            dto.setTerminalType(ConstantsUtil.TerminalType.SYSTEM.getType());
            if (list.size() == 0) {
                JsonResult jsonResult = scheduleSignService.cancelExamApply(dto);
                if (!"0".equals(jsonResult.getStatus())) {
                    return JsonResultUtil.failure(jsonResult.getMessage());
                }
            } else {
                JsonResult jsonResult = null;
                String userName = StringUtils.isBlank(dto.getUserName()) ? dto.getReqUser() : dto.getUserName();
                dto.setUserId(userName);
                dto.setUserName(userName);
                dto.setStaffNo(userName);
                if (StringUtils.isBlank(list.get(0).getExamStatus())) {
                    log.info("取消预约");
                    jsonResult = examApplyService.delApm(dto);
                } else {
                    log.info("取消报道");
                    jsonResult = examApplyService.delSign(dto);
                }
                if (!"0".equals(jsonResult.getStatus())) {
                    return JsonResultUtil.failure(jsonResult.getMessage());
                }
                jsonResult = scheduleSignService.cancelExamApply(dto);
                if (!"0".equals(jsonResult.getStatus())) {
                    return JsonResultUtil.failure(jsonResult.getMessage());
                }
                List<String> applyNos2 = CommonUtil.mergeNo2ApplyNos(dto.getMergeNo());
                ea_.setApplyNos(applyNos2);
                ea_.setActType(ConstantsUtil.ActType.CANCEL.getType());
                ea_.setMergeNo(dto.getMergeNo());
                ea_.setTerminalType(dto.getTerminalType());
                String itemNameStr2 = "";
                for (ExamApplyItemDto applyItem2 : items) {
                    itemNameStr2 = itemNameStr2 + applyItem2.getItemName() + ";";
                }
                ea_.setItemNameStr(itemNameStr2);
                configService.isScheduleSync(ea_, ea_.getActType(), ConstantsUtil.ScheduleStatus.NINE.getStatus());
                return JsonResultUtil.success("操作成功");
            }
        }
        String userName2 = StringUtils.isBlank(dto.getUserName()) ? dto.getReqUser() : dto.getUserName();
        DictUsersDto obj = new DictUsersDto();
        obj.setName(userName2);
        obj.setUserId(userName2);
        obj.setIpAddress("127.0.0.1");
        ea_.setTerminalType(ConstantsUtil.TerminalType.SYSTEM.getType());
        commonServiceImpl.addExamScheduleAct(ea_, obj);
        return JsonResultUtil.success("成功");
    }

    @Override
    public int insertSelective(ExamSchedule entity) {
        return examScheduleMapper.insert(entity);
    }

    @Override
    public boolean printCntPlusOne(ExamApplyDto dto) {
        ExamApplyItemDto examApplyItemDto = new ExamApplyItemDto();
        if (StringUtils.isNotBlank(dto.getMergeNo())) {
            String[] mergeNos = dto.getMergeNo().split(",");
            List<String> applyNos = new ArrayList<String>();
            for (String str : mergeNos) {
                int idx = str.lastIndexOf("-");
                String applyno = str.substring(0, idx);
                applyNos.add(applyno);
            }
            examApplyItemDto.setMergeNos((List) applyNos);
        } else {
            examApplyItemDto.setApplyNo(dto.getApplyNo());
        }
        List<ExamApplyItemDto> itemDtoList = examApplyItemMapper.getList(examApplyItemDto);
        if (itemDtoList != null && !itemDtoList.isEmpty()) {
            boolean result = examScheduleMapper.printCntPlusOne(itemDtoList.get(0).getScheduledId());
            List<ExamApplyDto> list = examApplyMapper.findByApplyNo(dto);
            if (result && list != null && !list.isEmpty()) {
                ExamApplyDto ea = list.get(0);
                DictUsersDto obj = commonServiceImpl.dictUsers(dto);
                if (StringUtils.isBlank(ea.getExamStatus()) && ConstantsUtil.ScheduleStatus.EIGHT.getStatus().equals(ea.getScheduleStatus())) {
                    ea.setActType(ConstantsUtil.ActType.SCHE_PRINT.getType());
                } else if ("10,20,40,50".contains(ea.getExamStatus())) {
                    ea.setActType(ConstantsUtil.ActType.SIGN_PRINT.getType());
                }
                ea.setTerminalType(dto.getTerminalType());
                commonServiceImpl.addExamScheduleAct(ea, obj);
            }
            return result;
        }
        return false;
    }

    @Override
    public int editExamScheduleById(ExamSchedule entity) {
        UpdateWrapper<ExamSchedule> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("SCHEDULED_ID", entity.getScheduledId());
        return examScheduleMapper.update(entity, updateWrapper);
    }

    @Override
    public Map<String, Object> getScheduleQueueDetailSum(ExamScheduleDto dto) {
        boolean isExamClass4Organ = configService.getOrganExamClassList().contains(dto.getExamClass());
        String isApmFlag = "0";
        dto.setIsApmFlag(isApmFlag);
        try {
            List<String> queueNames = new ArrayList<>();
            if (StringUtils.isNotBlank(dto.getQueueName())) {
                queueNames = CommonUtil.split2List(dto.getQueueName());
                dto.setQueueName(null);
            } else {
                DictExamQueueDto dictExamQueueDto = new DictExamQueueDto();
                dictExamQueueDto.setDeptCode(dto.getDeptCode());
                dictExamQueueDto.setExamClass(dto.getExamClass());
                List<DictExamQueue> dictExamQueueList = dictExamQueueService.getQueueNameList(dictExamQueueDto);
                if (CollectionUtils.isNotEmpty(dictExamQueueList)) {
                    return new HashMap<>();
                }
                for (DictExamQueue queue : dictExamQueueList) {
                    queueNames.add(queue.getQueueName());
                }
            }
            dto.setQueueNames(queueNames);
            String startDate = dto.getStartDate();
            String endDate = dto.getEndDate();
            if (StringUtils.isBlank(startDate)) {
                startDate = dto.getYear() + "-" + dto.getMonth() + "-01";
                endDate = DateUtil.getMaxDayOfThisMonth(dto.getYear(), dto.getMonth());
            }
            List<String> dateList = DateUtil.findDaysStr(startDate, endDate);
            List<String> apmSumList = new ArrayList<>();
            for (String date : dateList) {
                dto.setScheduledDate(date);
                dto.setWeekDate(DateUtil.getWeek(date));
                DictScheduleApmDto dsaDto = new DictScheduleApmDto();
                dsaDto.setQueueNames(dto.getQueueNames());
                dsaDto.setScheduleApm(dto.getScheduleApm());
                dsaDto.setWeekDate(dto.getWeekDate());
                dsaDto.setScheduleDate(dto.getScheduledDate());
                List<DictScheduleApm> liNormal = dictScheduleApmService.getNormalSchedule(dsaDto);
                List<DictScheduleApm> liDateSpeci = dictScheduleApmService.getDateScheduleApms(dsaDto);
                if (CollectionUtils.isNotEmpty(liNormal)) {
                    apmSumList.add("");
                }
                // 只有特殊日期的情况
                else if (CollectionUtils.isNotEmpty(liDateSpeci)) {
                    List<DictScheduleApm> liApm = getScheduleRegular(liDateSpeci, null, liNormal);
                    List<ExamSchedule> liExam = examScheduleMapper.getExamSchedule(dto);
                    List<ScheduleDetailDto> liDto = getExamSchedule4Ratio(liApm, liExam, isExamClass4Organ, dto);
                    List<Map<String, String>> lima = getScheduleDataGrid(liDto, queueNames, isExamClass4Organ, isApmFlag, "");
                    for (Map<String, String> apmMap : lima) {
                        if ("合计".equals(apmMap.get("apm"))) {
                            apmSumList.add(apmMap.get("apmHj"));
                        }
                    }
                } else {
                    List<DictScheduleApm> liWeekDateSpeci = dictScheduleApmService.getWeekDateScheduleApms(dsaDto);
                    List<DictScheduleApm> liApm = getScheduleRegular(liDateSpeci, liWeekDateSpeci, liNormal);
                    List<ExamSchedule> liExam = examScheduleMapper.getExamSchedule(dto);
                    List<ScheduleDetailDto> liDto = getExamSchedule4Ratio(liApm, liExam, isExamClass4Organ, dto);
                    List<Map<String, String>> lima = getScheduleDataGrid(liDto, queueNames, isExamClass4Organ, isApmFlag, "");
                    for (Map<String, String> apmMap : lima) {
                        if ("合计".equals(apmMap.get("apm"))) {
                            apmSumList.add(apmMap.get("apmHj"));
                        }
                    }
                }
            }
            Map<String, Object> map = new HashMap<>();
            String title = "已约申请单数 / 限制申请单数";
            if (isExamClass4Organ) {
                boolean isShowApplyNumber = configService.isOpenConfig(ConstantsUtil.ConfigName.IS_SHOW_APPLY_NUMBER.getKey());
                if (isShowApplyNumber) {
                    title = "已预约占用系数 / 系数限制";
                } else {
                    title = "已约申请单数 / 已预约占用系数 / 系数限制";
                }
            }
            map.put("title", title);
            map.put("apmSum", apmSumList);
            return map;
        } catch (Exception e) {
            log.error("getScheduleQueueDetailSum异常", e);
            return null;
        }
    }

    @Override
    public List<ExamApplyDto> getExamSchedule(ExamApplyDto dto) {
        return examApplyMapper.getExamSchedule(dto);
    }

    @Override
    public int updateExamSchedule(ExamScheduleDto dto) {
        return examScheduleMapper.updateExamSchedule(dto);
    }

    @Override
    public List<ExamSchedule> getExamScheduleByNxtApm(ExamScheduleDto dto) {
        QueryWrapper<ExamSchedule> qw = new QueryWrapper<>();
        qw.like("NEXT_APM_RATIO", dto.getApmCode());
        qw.eq("SCHEDULED_DATE", dto.getScheduledDate());
        return examScheduleMapper.selectList(qw);
    }

    @Override
    public List<ExamSchedule> selectList(ExamScheduleDto dto) {
        Map<String, String> map = new HashMap<>();
        map.put("SCHEDULED_ID", dto.getScheduledId());
        map.put("SCHEDULED_DATE", dto.getScheduledDate());

        QueryWrapper<ExamSchedule> qw = new QueryWrapper<>();
        qw.allEq(map, false);
        return examScheduleMapper.selectList(qw);
    }

    /**
     * 报到率统计
     *
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> checkRateCount(ExamScheduleDto dto) {
        dto.setExamClasses(CommonUtil.split2List(dto.getExamClass()));
        dto.setPerformDepts(CommonUtil.split2List(dto.getPerformDeptName()));
        dto.setQueueNames(CommonUtil.split2List(dto.getQueueName()));
        List<ExamScheduleDto> list = examScheduleMapper.checkRateCount(dto);

        Map<String, Object> queueMap = new HashMap<String, Object>();
        Map<String, Object> queueSize = new HashMap<String, Object>();
        Map<String, List<ExamScheduleDto>> dateMap = new LinkedHashMap<String, List<ExamScheduleDto>>();
        List<String> column = new ArrayList<String>();
        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        for (ExamScheduleDto scheduleDto : list) {
            if (!column.contains(scheduleDto.getQueueName())) {
                column.add(scheduleDto.getQueueName());
            }
            if (dateMap.containsKey(scheduleDto.getScheduledDate())) {
                List<ExamScheduleDto> dataList = dateMap.get(scheduleDto.getScheduledDate());
                ExamScheduleDto data = new ExamScheduleDto();
                data.setScheduledDate(scheduleDto.getScheduledDate());
                data.setQueueName(scheduleDto.getQueueName());
                data.setCheckRate(scheduleDto.getCheckRate());
                dataList.add(data);
            } else {
                List<ExamScheduleDto> dataList = new ArrayList<ExamScheduleDto>();
                ExamScheduleDto data = new ExamScheduleDto();
                data.setScheduledDate(scheduleDto.getScheduledDate());
                data.setQueueName(scheduleDto.getQueueName());
                data.setCheckRate(scheduleDto.getCheckRate());
                dataList.add(data);
                dateMap.put(scheduleDto.getScheduledDate(), dataList);
            }
            if (queueMap.size() > 0) {
                double queueDate = (queueMap.get(scheduleDto.getQueueName()) == null) ? 0.0 : Double.parseDouble(queueMap.get(scheduleDto.getQueueName()) + "");
                queueMap.put(scheduleDto.getQueueName(), BigDecimalUtil.add(queueDate, scheduleDto.getCheckRate()));
            } else {
                queueMap.put(scheduleDto.getQueueName(), scheduleDto.getCheckRate());
            }
            double queueCount = (queueSize.get(scheduleDto.getQueueName()) == null) ? 0.0 : Double.parseDouble(queueSize.get(scheduleDto.getQueueName()) + "");
            queueSize.put(scheduleDto.getQueueName(), queueCount + 1.0);
        }
        List<ExamScheduleDto> data2 = new ArrayList<>();
        for (String key : dateMap.keySet()) {
            ExamScheduleDto exam = new ExamScheduleDto();
            exam.setScheduledDate(key);
            List<ExamScheduleDto> dataList2 = dateMap.get(key);
            exam.setQueueDate(dataList2);
            data2.add(exam);
        }
        Map<String, Object> queueAvg = new HashMap<>();
        for (String queue : queueMap.keySet()) {
            double qAvg = BigDecimalUtil.divide(Double.parseDouble(queueMap.get(queue) + ""), Double.parseDouble(queueSize.get(queue) + ""));
            queueAvg.put(queue, String.valueOf((int) BigDecimalUtil.round(qAvg, 2)));
        }
        resultMap.put("column", column);
        resultMap.put("data", data2);
        resultMap.put("queueAvg", queueAvg);
        return resultMap;
    }

    @Override
    public int getCount(ExamScheduleDto dto) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("SCHEDULED_DATE", dto.getScheduledDate());
        map.put("APM_CODE", dto.getApmCode());
        QueryWrapper<ExamSchedule> qw = (QueryWrapper<ExamSchedule>) new QueryWrapper();
        qw.allEq((Map) map, false);
        return examScheduleMapper.selectCount((Wrapper) qw);
    }

    private String queueAlias2Name(ExamScheduleDto dto) {
        String queueName = dto.getQueueName();
        DictExamQueueDto dictExamQueueDto = new DictExamQueueDto();
        dictExamQueueDto.setDeptCode(dto.getDeptCode());
        dictExamQueueDto.setExamClass(dto.getExamClass());
        dictExamQueueDto.setQueueAlias(dto.getQueueName());
        List<DictExamQueue> deqList = (List<DictExamQueue>) dictExamQueueService.getQueueNameList((DictExamQueue) dictExamQueueDto);
        if (deqList != null && !deqList.isEmpty() && StringUtils.isNotBlank(deqList.get(0).getQueueName())) {
            queueName = deqList.get(0).getQueueName();
        }
        return queueName;
    }

    @Override
    public Map<String, Object> getOragnsTotal(ExamScheduleDto dto) {
        String apmCodeo = dto.getApmCode();
        String apmCodet = dto.getApmCode();
        String apmCodes = dto.getApmCode();
        int i = 1;
        for (String apmCode : dto.getApmCodes()) {
            if (i == 1) {
                apmCodeo = apmCode;
            }
            if (i == 2) {
                apmCodet = apmCode;
            }
            if (i == 3) {
                apmCodes = apmCode;
            }
            ++i;
        }
        String apmCode2 = apmCodeo;
        String apmCode3 = apmCodet;
        String apmCode4 = apmCodes;
        QueryWrapper<ExamSchedule> queryWrapper = (QueryWrapper<ExamSchedule>) new QueryWrapper();
        queryWrapper.eq("QUEUE_NAME", dto.getQueueName());
        queryWrapper.eq("SCHEDULED_DATE", dto.getScheduledDate());
//        queryWrapper.and(wrapper -> (QueryWrapper) ((QueryWrapper) ((QueryWrapper) ((QueryWrapper) ((QueryWrapper) ((QueryWrapper) ((QueryWrapper) wrapper.in("APM_CODE", (Collection) dto.getApmCodes())).or()).like("NEXT_APM_RATIO", apmCode2)).or()).like("NEXT_APM_RATIO", apmCode3)).or()).like("NEXT_APM_RATIO", apmCode4));
        queryWrapper.in("APM_CODE", dto.getApmCodes())
                .or().like("NEXT_APM_RATIO", apmCode2)
                .or().like("NEXT_APM_RATIO", apmCode3)
                .or().like("NEXT_APM_RATIO", apmCode4);
        List<ExamSchedule> examScheduleList = (List<ExamSchedule>) examScheduleMapper.selectList((Wrapper) queryWrapper);
        double organs = 0.0;
        int count = 0;
        if (examScheduleList != null && examScheduleList.size() > 0) {
            for (ExamSchedule es : examScheduleList) {
                if (dto.getApmCodes().contains(es.getApmCode())) {
                    double organSum = (es.getOrgans() == null) ? 0.0 : es.getOrgans();
                    organs += organSum;
                    ++count;
                    if (!StringUtils.isNotBlank(es.getNextApmRatio())) {
                        continue;
                    }
                    String[] split;
                    String[] nextApmRatioArr = split = es.getNextApmRatio().split("\\|");
                    for (String nextApmRatios : split) {
                        String[] apmRatioArr = nextApmRatios.split("=");
                        if (!dto.getApmCodes().contains(apmRatioArr[0])) {
                            organs -= Double.parseDouble(apmRatioArr[1]);
                        }
                    }
                } else {
                    if (!StringUtils.isNotBlank(es.getNextApmRatio())) {
                        continue;
                    }
                    String[] split2;
                    String[] nextApmRatioArr2 = split2 = es.getNextApmRatio().split("\\|");
                    for (String nextApmRatios2 : split2) {
                        String[] apmRatioArr2 = nextApmRatios2.split("=");
                        if (dto.getApmCodes().contains(apmRatioArr2[0])) {
                            organs += Double.parseDouble(apmRatioArr2[1]);
                        }
                    }
                }
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("organs", organs);
        map.put("count", count);
        return map;
    }

    @Override
    public List<RuleDto.ComboBox> getApmRegularTypeList(ExamScheduleDto dto) {
        boolean isExamClass4Organ = configService.getOrganExamClassList().contains(dto.getExamClass());
        dto.setIsExamClassRatio(isExamClass4Organ);
        List<String> queueNames = new ArrayList<>();
        // 如果是合计或者为空 则根据检查类别和科室查询所有可用的队列
        if ("合计".equals(dto.getQueueName()) || "".equals(dto.getQueueName())) {
            DictExamQueueDto dictExamQueueDto = new DictExamQueueDto();
            dictExamQueueDto.setDeptCode(dto.getDeptCode());
            dictExamQueueDto.setExamClass(dto.getExamClass());
            List<DictExamQueue> dictExamQueueList = dictExamQueueService.getQueueNameList(dictExamQueueDto);
            if (CollectionUtils.isNotEmpty(dictExamQueueList)) {
                for (DictExamQueue queue : dictExamQueueList) {
                    queueNames.add(queue.getQueueName());
                }
            }
        } else {
            queueNames = CommonUtil.split2List(dto.getQueueName());
        }
        dto.setQueueNames(queueNames);
        // 如果时段是合计 则不关联时段
        if ("合计".equals(dto.getScheduleApm())) {
            dto.setScheduleApm(null);
        } else if (StringUtils.isNotBlank(dto.getApmFlag())) {
            if (ConstantsUtil.DictScheduleApmFlag.MORNING.getValue().equals(dto.getApmFlag())) {
                dto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.MORNING.getKey());
            } else if (ConstantsUtil.DictScheduleApmFlag.AFTERNOON.getValue().equals(dto.getApmFlag())) {
                dto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.AFTERNOON.getKey());
            } else if (ConstantsUtil.DictScheduleApmFlag.NIGHT.getValue().equals(dto.getApmFlag())) {
                dto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.NIGHT.getKey());
            } else if (ConstantsUtil.DictScheduleApmFlag.NOON.getValue().equals(dto.getApmFlag())) {
                dto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.NOON.getKey());
            } else if ("合计".equals(dto.getApmFlag())) {
                dto.setApmFlag(null);
            } else {
                dto.setApmFlag(ConstantsUtil.DictScheduleApmFlag.ALLDAY.getKey());
            }
        }
        // 查询时段列表
        DictScheduleApmDto dictScheduleApmDto = new DictScheduleApmDto();
        dictScheduleApmDto.setQueueNames(dto.getQueueNames());
        dictScheduleApmDto.setScheduleDate(dto.getScheduledDate());
        dictScheduleApmDto.setApmFlag(dto.getApmFlag());
        dictScheduleApmDto.setScheduleApm(dto.getScheduleApm());
        dictScheduleApmDto.setWeekDate(DateUtil.getWeek(dto.getScheduledDate()));
        List<DictScheduleApmDto> dictScheduleApmDtoList = dictScheduleApmService.getScheduleApms(dictScheduleApmDto);

        List<String> scheduleApm_new = new ArrayList<>();
        List<String> scheduleApmCode_new = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dictScheduleApmDtoList)) {
            for (DictScheduleApmDto apmDto : dictScheduleApmDtoList) {
                scheduleApm_new.add(apmDto.getScheduleApm());
                scheduleApmCode_new.add(apmDto.getApmCode());
            }
        }
        dto.setScheduleApms(scheduleApm_new);
        dto.setScheduleApmCodes(scheduleApmCode_new);
        List<RuleDto.ComboBox> comboBoxList = new ArrayList<>();

        // 查询时段列表绑定的规则
        DictScheduleApmRegularDto dsarDto = new DictScheduleApmRegularDto();
        dsarDto.setScheduleApmCodes(dto.getScheduleApmCodes());
        List<DictScheduleApmRegularDto> dsarList = dictScheduleApmRegularService.selectRegularTypeGroupList(dsarDto);

        RuleDto.ComboBox all = new RuleDto.ComboBox("", "全部");
        comboBoxList.add(all);
        if (dsarList != null && !dsarList.isEmpty()) {
            for (DictScheduleApmRegularDto dsar : dsarList) {
                if (StringUtils.isNotBlank(dsar.getRegularType())
                        && ConstantsUtil.ScheduleRegularType.NUMBER.equals(dsar.getRegularType())) {
                    RuleDto.ComboBox comboBox = new RuleDto.ComboBox(dsar.getRegularId(), dsar.getRegularName());
                    if (comboBoxList.contains(comboBox)) {
                        continue;
                    }
                    comboBoxList.add(comboBox);
                }
            }
        }
        return comboBoxList;
    }
}
